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[@]} "
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
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[@]}'