I tried these variations, but none of them do nothing, i.e, do not print 5
linux@linux:~$ bash -c 'var=5 printf "$var"'
linux@linux:~$ bash -c "export var=5 echo $var"
linux@linux:~$ bash -c "export var=5 && echo $var"
linux@linux:~$ bash -c "var=5; echo $var"
linux@linux:~$ var=5 sudo printf "$var"
linux@linux:~$ var=5 sudo -E printf "$var"
linux@linux:~$ bash --version
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
bash -c 'var=5; echo "$var"'
works fine, f/e. However, when you pass the code tobash -c
in double quotes, the$var
gets replaced with the value ofvar
in the parent shell, before the copy ofbash
passed the-c
argument is even started, and thus before the assignment takes place. - Charles Duffyexport var=5 echo $var
exports a variable namedecho
. The related expressionvar=5 echo $var
calls echo with either one argument (the value of $var in the caller) or no arguments (if$var
is empty or unset in the caller) and the environment variable set to5
. But echo ignores its environment, so that doesn't change its behavior. - William Pursellvar=5
is stored into the environment of the called program (hereecho
orprintf
). But$val
is evaluated before the program is called.val=5 sh -c 'echo $val'
orval=5 sh -c "echo \$val"
will work, because the called programsh
will expand$val
. - Wiimm