8

I tried to define a variable in a 'sh -c' command string:

sh -c "TMP=??; echo $TMP;"

Nothing was printed.

Why can't I define a variable in a 'sh -c' string?

2
  • It works perfectly in my environment. What OS are you using, and which version of bash?
    – mrc02_kr
    Commented Sep 8, 2017 at 9:06
  • 1
    @mrc02_kr It would only work if $TMP is ?? before executing the line.
    – Kusalananda
    Commented Sep 8, 2017 at 9:08

2 Answers 2

14
sh -c 'TMP=??; echo $TMP;'

When using double quotes the parameter expansion occurs when the command line is built i.e. the shell does not see

TMP=??; echo $TMP;

as its parameter but

TMP=??; echo ;

if $TMP is empty in the calling shell environment.

2
  • 6
    Also note that if you expect ?? to be printed as opposed to the names of the non-hidden files in the current directory that consist of two characters, you'll need sh -c 'TMP=??; echo "$TMP"' Commented Sep 8, 2017 at 9:24
  • I realized I hadn't left appreciation. Thank you it helped a lot :D Commented Jan 14, 2019 at 6:49
9
sh -c 'TMP=??; echo "$TMP"'

With double quotes around the sh -c code, the $TMP is expanded by the interactive shell before the sh -c code executes. With single quotes, $TMP will be expanded inside the sh shell. (I've also properly quoted the $TMP variable expansion for echo).

Single quotes protects a string from variable expansions.

If you do not intend the ?? to be treated as a filename globbing pattern inside the sh -c script, then use

sh -c 'TMP="??"; echo "$TMP"'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .