I can't figure out how to declare a variable inside bash -c
command.
bash -c "var=3; echo $var"
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityLet's see what actually happens here:
$ set -x
$ bash -c "var=3; echo $var"
+ bash -c 'var=3; echo '
With set -x
you get a trace of what commands are actually executed (use set +x
to turn this off). Here we see that the $var
variable is expanded to an empty string before the child bash -c
shell even runs.
This is due to the double quoting of the argument to bash -c
, which will prompt the current shell to do variable expansion within the string. Since the var
variable is undefined or empty in the current shell, it's expansion is the empty string.
To protect a string from "interference" by the shell, use single quotes:
$ bash -c 'var=3; echo $var'
+ bash -c 'var=3; echo $var'
3
... or escape the $
(IMO not as nice):
$ bash -c "var=3; echo \$var"
+ bash -c 'var=3; echo $var'
3
Because $?
and $a
are evaluated in the calling shell.
bash -c 'cat /tmp/lol ; a=$?; if (( $a == 0)); then echo "2"; fi;'
bash -c "cat /tmp/l3ol ; a=$?; if (( "'$a'" == 0)); then echo '2'; fi;"
prints 2 as well? I dont have l3ol
file
May 13, 2018 at 9:20