I can't figure out how to declare a variable inside bash -c command.

bash -c "var=3; echo $var"

2 Answers 2


Let'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'

... or escape the $ (IMO not as nice):

$ bash -c "var=3; echo \$var"
+ bash -c 'var=3; echo $var'

Because $? and $a are evaluated in the calling shell.

bash -c 'cat /tmp/lol ; a=$?; if (( $a == 0)); then echo "2"; fi;'
  • Why 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
  • Because that evaluates $? in the calling shell. May 13, 2018 at 9:20
  • Oh... I finally get it... May 13, 2018 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .