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?

  • It works perfectly in my environment. What OS are you using, and which version of bash? – mrc02_kr Sep 8 '17 at 9:06
  • 1
    @mrc02_kr It would only work if $TMP is ?? before executing the line. – Kusalananda Sep 8 '17 at 9:08
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.

  • 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"' – Stéphane Chazelas Sep 8 '17 at 9:24
  • I realized I hadn't left appreciation. Thank you it helped a lot :D – Gwangmu Lee Jan 14 '19 at 6:49
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"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.