0
$ bash -c "for VAR in {0..9}; do echo $VAR; done;

And a shell script containing exactly what's in the quotes behaves as expected.

The result is 10 blank lines - no matter which way I mildly edit this line (i.e. /bin/bash or sh instead of bash, or using ${VAR}, "$VAR", "${VAR}", or a different variable name), and I get the same result outputting to a file.

If I use a variable name that I've set previously with just $ VAR=1, this will output 1, 10 times.

Both .bash & .bash_profile look completely normal for my user. This is driving me insane, but did I miss something very obvious here?

1
  • replace the double quotes with single quotes. -c invokes a subshell or a it spawns a new shell afaik.
    – Jetchisel
    Commented Mar 2, 2020 at 0:13

1 Answer 1

1

You can see what's happening by turning on debugging with set -x:

$ set -x
$ bash -c "for VAR in {0..9}; do echo $VAR; done;"
+ bash -c 'for VAR in {0..9}; do echo ; done;'

So, the double quotes around your -c expression are allowing the interactive parent shell to expand $VAR (to the empty string). It will work as you expect if you use single quotes:

bash -c 'for VAR in {0..9}; do echo $VAR; done;'

or escape the $:

bash -c "for VAR in {0..9}; do echo \$VAR; done;"
2
  • Thank you! I should've thought to use set -x, makes the issue pretty clear
    – oandersonm
    Commented Mar 2, 2020 at 0:16
  • @andersonm you're welcome - also notice that the brace expansion {0-9} is not expanded inside double quotes - that catches people out sometimes as well Commented Mar 2, 2020 at 0:19

You must log in to answer this question.

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