1

I simply don't understand

command-line (works):

$ someprog -flag 'key1=val 1,key2=val 2,key3=val 3'

sh direct (works):

#!/bin/sh
someprog -flag 'key1=val 1,key2=val 2,key3=val 3'

sh variable (fails):

#!/bin/sh
OPTSTR="'key1=val 1,key2=val 2,key3=val 3'"
someprog -flag "$OPTSTR"      #fails
someprog -flag ${OPTSTR}      #fails
someprog -flag $OPTSTR        #fails
eval "someprog -flag $OPTSTR" #works

1 Answer 1

2

In the first two examples you quote your argument. Those quotes are only seen by your shell, which treats the whole string as a single argument instead of splitting it on the spaces. The quotes itself are not seen by the program.

When typing OPTSTR="'key1=val 1,key2=val 2,key3=val 3'" the content of your variable contains the single quotes, and will therefore later be given to your program. Your program sees the quotes, does not expect them and therefore fails.

Simply use:

OPTSTR="key1=val 1,key2=val 2,key3=val 3"
someprog -flag "$OPTSTR"

The difference between single and double quotes is, whether you want your shell to replace variables and such or not.

5
  • from the first 2 examples, the program does expect a singly-quoted string as an argument Commented Feb 20, 2015 at 7:15
  • 1
    no it does not. ;) those quotes are handled by your shell. the actual program does never see those quotes. Commented Feb 20, 2015 at 7:21
  • wait, are we talking about the command-line and sh direct examples? Commented Feb 20, 2015 at 7:23
  • about both. in both cases your shell is evaluating the line. (in the one case you have an interactive shell, in the other case it is used non-interactive.) Commented Feb 20, 2015 at 7:25
  • ah you are indeed right! all these quotes are confusing me :/ Thanks for your patience and your help! Commented Feb 20, 2015 at 7:31

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.