0
votes

I tried these variations, but none of them do nothing, i.e, do not print 5

enter image description here

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.
Some of them came close to working, except for the usage of the wrong kind of quotes. bash -c 'var=5; echo "$var"' works fine, f/e. However, when you pass the code to bash -c in double quotes, the $var gets replaced with the value of var in the parent shell, before the copy of bash passed the -c argument is even started, and thus before the assignment takes place. - Charles Duffy
...I've added a second duplicate to the list covering that case. - Charles Duffy
export var=5 echo $var exports a variable named echo. The related expression var=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 to 5. But echo ignores its environment, so that doesn't change its behavior. - William Pursell
var=5 is stored into the environment of the called program (here echo or printf). But $val is evaluated before the program is called. val=5 sh -c 'echo $val' or val=5 sh -c "echo \$val" will work, because the called program sh will expand $val. - Wiimm