[Discuss] How to keep '-' in bash args
pw
p.willis at telus.net
Wed May 2 06:55:44 PDT 2007
noel at natnix.com wrote:
> Ummm, what are you trying to do exactly? There are simpler ways of
> breaking up args and pattern-matching than resorting to awk and sed:
>
> args="1 2 3 -4 -5 -6"
> for arg in $args; do
> case $arg in
> -*) echo "opt: [$arg]" ;;
> *) echo "noopt: [$arg]" ;;
> esac
> done
I want to pass arguments to a shell script in the format:
script -flag1 value1 -flag2 value2 -flagn valuen
I want to be able to put the flags and accompanying values
in any order.
ie:
sh script.sh -flag7 value7 -flag3 value3 -flag1 value1
I want it to work just like a standard flagged command line
application without having to apply any special input
formatting to the arguments.
ie:
sh script.sh -flag1 value1 -flag2 value2 -flagn valuen
instead of:
sh script.sh "-flag1 value1 -flag2 value2 -flagn valuen"
I finally rattled my head and remembered 'eval'. (duh!)
#!/bin/bash
#test4.sh
for ARG in `seq 1 256`; do
eval C='$'$ARG;
NEXT=`expr $ARG + 1`;
eval D='$'$NEXT;
L=`echo "$C" | wc -m |awk '{print $0-1}'`
if [ "$L" -ne 0 ]; then
FLAG=`printf '%s\n' "$C" | sed -e "s/\ //g" | \
awk '{A=index($0,"-"); if(A==1){print "1" }else{ print "0"}}'`;
if [ "$FLAG" = "1" ]; then
echo "$C is a flag"
case "$C" in
"-flag1")
FLAG_ONE=$D
;;
"-flag2")
FLAG_TWO=$D
;;
?)
;;
esac
else
echo "$C is not a flag"
fi
else
break
fi
done
#PROGRAM USES ARGS HERE
echo "$FLAG_ONE $FLAG_TWO"
#END OF SCRIPT
run:
test4.sh -flag1 one -flag2 two
output:
-flag1 is a flag
one is not a flag
-flag2 is a flag
two is not a flag
one two
run:
test4.sh -flag2 two -flag1 one
output:
-flag2 is a flag
two is not a flag
-flag1 is a flag
one is not a flag
one two
Peter
More information about the Discuss
mailing list