How to assign shell variables inside sh -c "..." command?

While doing

jeremy@home:/$DOG=happy; echo $DOG;

you get a conclusion

happy

However, when you do 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 -c "DOG=happy; echo '$DOG';"

you get only an empty string. How it is? How can I set a variable from sh -c command?

+3
source share
2 answers

Escape the dollar sign ( \$).

> sh -c "DOG=happy; echo \$DOG;"
happy

Another option is to use single quotes instead of double quotes - variables are not evaluated inside single quotes, so they $DOGwill be passed in shfor evaluation.

> sh -c 'DOG=happy; echo $DOG'
happy

, sh, , , .

+7

:

sh -c 'DOG=happy; echo $DOG;'

'$'

sh -c "DOG=happy; echo \$DOG;"
+5

Source: https://habr.com/ru/post/1785384/


All Articles