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?
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.
??
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
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"'
$TMP
is??
before executing the line.