Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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?

like image 878
buddy Avatar asked Jan 03 '23 10:01

buddy


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
like image 141
PSkocik Avatar answered Jan 13 '23 13:01

PSkocik


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.

like image 43
Ardit Avatar answered Jan 13 '23 15:01

Ardit