1

I want to define variable inside bash -c like following one. but the script outputs nothing. Any idea?

bash -c "FOOBARLIST=(foo bar) ; echo ${FOOBARLIST[@]} "
k23j4
  • 723
  • 2
  • 8
  • 15

2 Answers2

1

You need to use single quotes here.

With double quotes, ${FOOBARLIST[@]} is expanded by the outer shell before the inner shell even runs. Since FOOBARLIST is undefined in the outer shell, ${FOOBARLIST[@]} expands to nothing and the inner shell executes:

FOOBARLIST=(foo bar) ; echo
user4815162342
  • 141,790
  • 18
  • 296
  • 355
1

The trouble is not caused by the script you pass to bash -c but by the current instance of the shell (bash or whatever it is).

The script is an argument in a command line. Because it is enclosed in double quotes, the shell does variable expansion in it. It replaces ${FOOBARLIST[@]} with the value of the FOOBARLIST array defined in the current environment.

But there isn't any FOOBARLIST variable in the current environment, ${FOOBARLIST[@]} is replaced by an empty strings and the command it runs is:

bash -c "FOOBARLIST=(foo bar) ; echo "

The simplest solution is to enclose the script into single quotes (apostrophes). This way the current shell doesn't replace anything in it and passes it as is to bash -c:

bash -c 'FOOBARLIST=(foo bar); echo ${FOOBARLIST[@]}'
axiac
  • 68,258
  • 9
  • 99
  • 134