简体   繁体   中英

Parsing input options containing whitespaces in a bash script

I have a bash script parsing input option with a block of code like the following

for WORD in "$@" ; do
 case $WORD in
  --*) true ;
    case $WORD in
      --opt1=*) 
          OPT1=${WORD/--opt1=/}
          shift ;;
      --opt2=*) 
          OPT2=${WORD/--opt2=/}
          shift ;;
      *) echo "Unrecognized argument $WORD"      
          ;; 
    esac ;;
  *) echo "Option $WORD not starting with double dash."  
  ;; 
 esac
done

The script is invoked by another parent program which creates the entire command line. The output created by this parent program looks like

./childscript.sh "--opt1=value1 --opt2=value2"

The problems appear when the generated line looks like

./childscript.sh "--opt1='value11 value12' --opt2=value2"

The scripts complains saying

Option value12 not starting with double dash.

How can I modify the child bash code to make it understand white spaces inside the input options?

I don't think the generated line is what you think it is.

Your code works completely fine for me if I simply invoke it directly. With added echoes to check that the values are being stored in the right place:

$ ./child.sh --opt1='v1 v2' --opt2='v3 v4'
OPT1='v1 v2'
OPT2='v3 v4'

You should be able to confirm this. Your problem isn't in making the child script accept arguments like these, it's in having the parent script invoke it correctly.

And by the way, you don't actually want to run something like this:

./childscript.sh "--opt1=value1 --opt2=value2"

That will cause that entire string ( --opt1=value1 --opt2=value2 ) to be read as a single argument. I suspect that you haven't told us the full story on the way the parent script is calling this. If you show us those details, we can probably help out more - or maybe this is enough of a hint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM