[Discuss] How to keep '-' in bash args

noel at natnix.com noel at natnix.com
Wed May 2 08:54:20 PDT 2007


Whoa, that's a bit compicated.  Try using "$#" and "shift" instead of
seq, eval, awk, etc:

# parse command-line args in bash
while [ $# -gt 0 ]; do
    case "$1" in
        -opt1) shift; opt1_val="$1" ;;     # option with value arg
        -opt2) opt2_val=true ;;            # plain option
        --) shift; break ;;                # end of options
        -*) echo "unrecognized option: $1"; exit 1 ;;
        *) break ;; # not an option, start of arguments
    esac
    shift
done

(One thing about getopt and friends is that it's very easy to write it
yourself.)

--Noel


On Wed, May 02, 2007 at 06:55:44AM -0700, pw wrote:
> 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
> 
> _______________________________________________
> Discuss mailing list
> Discuss at vlug.org
> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss


More information about the Discuss mailing list