When you execute
jeremy@home:/$DOG=happy; echo $DOG;
you get the output
happy
However, when you execute jeremy@home:/$sh -c "DOG=happy; echo $DOG;"
or even
jeremy@home:/$sh -c "DOG=happy; echo "$DOG";"
or
jeremy@home:/$sh -c "DOG=happy; echo \"$DOG\";"
or
jeremy@home:/$sh开发者_JAVA技巧 -c "DOG=happy; echo '$DOG';"
you get only a blank line. How is this so? How can I actually set a variable from inside a sh -c command?
Escape the dollar sign (\$
).
> sh -c "DOG=happy; echo \$DOG;"
happy
Another option is to use single quotes instead of double quotes - variables aren't evaluated inside of single quotes, so the $DOG
will be passed through to sh
for evaluation.
> sh -c 'DOG=happy; echo $DOG'
happy
However, if you need to both substitute in variables before passing to sh
, and also pass certain variables through, it's usually easiest to just escape the ones you do want to pass through.
The good command is:
sh -c 'DOG=happy; echo $DOG;'
or you can just escape the '$' sign
sh -c "DOG=happy; echo \$DOG;"
精彩评论