0

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.
jww
  • 97,681
  • 90
  • 411
  • 885
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
  • 3
    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 May 04 '19 at 21:51
  • 1
    ...I've added a second duplicate to the list covering that case. – Charles Duffy May 04 '19 at 21:54
  • 1
    `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 May 04 '19 at 22:11
  • 1
    `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 May 04 '19 at 23:02

0 Answers0