How do I parse command line arguments(as key value pair) in Bash? with arguments say with nested delimiters

Viewed 3479

When i parse command line arguments with equal to as delimiter which can have nested equal to. CC="arm-oe-linux --sysroots=/home/somelocation" CFLAGS="" I had tried this:

for ARGUMENT in "$@"
do
    KEY=$(echo $ARGUMENT | cut -f1 -d=)
    VALUE=$(echo $ARGUMENT | cut -f2 -d=)   

   echo $KEY
   echo $VALUE
   echo "*******************"

    case "$KEY" in

            CC)    CC=${VALUE} ;;     
        CFLAGS)    CFLAGS=${VALUE} ;;     
             *)   
    esac    
done

That But for nested = this does not help. Any suggestions?

2 Answers

Use the shell language to do the string stuff. No need to create expensive processes just to split a string on the first equal sign.

(Also, it's generally recommended to use lower case variable names for variables that are not exported.)

for argument; do #syntactic sugar for: for argument in "$@"; do
    key=${argument%%=*}
    value=${argument#*=}

    echo "$key"
    echo "$value"
    echo "*******************"

    case "$key" in

            CC)    CC=$value;;
        CFLAGS)    CFLAGS=$value;;
    esac    
done

This happens because of the spaces that the arguments contain. Please try putting single quotes (answer edited) around your variable substitutions to keep them from being parsed i.e.:

./yourscriptname.sh CC='"arm-oe-linux --sysroots=/home/somelocation"' CFLAGS='""'

Also, your arguments contain "=" within more than once. In order to avoid this you may improve the script as following:

for ARGUMENT in "$@"
do
   eval $ARGUMENT 
done
echo -e CC=$CC
echo -e CFLAGS=$CFLAGS

Keep in mind to put the single quotes as well. For more information you may see the eval man page.

Related