OS: Ubuntu 16.04.3
Shell: Bash 4.3.48
I know that is possible to temporarily change the content of a variable as in var=value command
, being probably IFS= read -r var
the most notable case of this.
And, thanks to Greg's wiki, I also understand:
# Why this
foo() { echo "$var"; }
var=value foo
# And this does work
var=value; echo "$var"
# But this doesn't
var=value echo "$var"
What escapes my understanding is this:
$ foo() { echo "${var[0]}"; }
$ var=(bar baz) foo
(bar baz)
As far as I know (and following the logic of previous examples), it should print bar
, not (bar baz)
.
Does this only happen to me? Is this the intended behavior and I'm missing something? Or is this a bug?
export var=(foo bar); echo "${var[0]}"
it printsfoo
, not(foo bar)
. – nxnev Dec 21 '17 at 18:35export
it shows:declare -ax var=([0]="foo" [1]="bar")
– jesse_b Dec 21 '17 at 18:39export i_am_array=(foo bar); /usr/bin/env | grep i_am_array
gives no output here. – derobert Dec 21 '17 at 18:47foo() { declare -p var; } ; var=(bar baz) foo
givesdeclare -x var="(bar baz)"
confirming its being treated as a string, not an array – derobert Dec 21 '17 at 18:49export var=(foo bar); declare -p var
also printsdeclare -ax var='([0]="foo" [1]="bar")'
. So usingdeclare
to check the attributes ofvar
displays both as an array and as a string. It could be that mantainers decided to add support to arrays as env variables but it's still an ongoing work? – nxnev Dec 21 '17 at 18:59var[0]=blahblah foo
– ilkkachu Dec 21 '17 at 19:27declare -p var
tofoo()
, it seems that variable is unset:bash: declare: var: not found
. So using different approachesvar
could be a string, an array or unset. – nxnev Dec 21 '17 at 19:38var=(aa bb); var[0]=what foo
printsaa
, so the assignment to a member of an array doesn't happen at all. – ilkkachu Dec 21 '17 at 19:57VAR=VALUE some-command
construction. Also added link to it in my answer. – MiniMax Dec 22 '17 at 17:59