开发者

How do you assign shell variables inside of a sh -c "..." command?

开发者 https://www.devze.com 2023-02-04 20:45 出处:网络
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;\"

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;"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号