1

According to my bash man page: If the word is double-quoted ${name[@]} expands each element of name to a separate word.

This usually leads to exactly the expected behavior:

$ a=("foo 1" "bar 2")
$ for i in "${a[@]}"; do echo $i; done
foo 1
bar 2
$ size(){ echo $#;};size "${a[@]}"
2
$ [ "${a[@]}" = "foo 1 bar 2" ]&&echo ok
bash: [: too many arguments

But sometimes it does not:

$ [[ "${a[@]}" == "foo 1 bar 2" ]] && echo ok
ok
$ case "${a[@]}" in "foo 1 bar 2") echo ok; esac
ok

In those cases it seems to get evaluated into a single string. - This makes sense, but is a bit surprising. - I expected it to be equal to "foo 1" "bar 2" and therefore cause a syntax error.

Is there a rule in which context it is evaluated which way? (I couldn't find the right section in the bash man page.)

Additional question: Is there a case in which "${a[@]}" is handled differently from ${a[@]}?

3
  • Remove the " and use ${a[@]} instead of "${a[@]}". Commented Jun 7, 2013 at 10:57
  • case ${a[@]} in "foo 1 bar 2") echo ok; esac -> ok Commented Jun 7, 2013 at 11:11
  • Use set -xv to view how bash processes the commands. Commented Jun 7, 2013 at 11:47

2 Answers 2

2

No word splitting or glob expansion is performed for [[.

From Bash FAQ:

Since word splitting is not performed when expanding shell variables in all
operands of the [[ command, this allows users to quote patterns as they wish
when assigning the variable, then expand the values to a single string that
may contain whitespace.

Additionally, refer to Word Splitting:

  • Word splitting is not performed on expansions inside Bash keywords such as [[ ... ]] and case.
  • Word splitting is not performed on expansions in assignments. Thus, one does not need to quote anything in a command like these:
    • foo=$bar
    • bar=$(a command)
    • logfile=$logdir/foo-$(date +%Y%m%d)
    • PATH=/usr/local/bin:$PATH ./myscript
Sign up to request clarification or add additional context in comments.

Comments

-1

The man page did say to a separate word and did not say into one word. The a array "${a[@]}" is not the same thing as "foo 1 bar 1". This only returns 1 big string:

for i in "foo 1 bar 1"; do echo $i; done

1 Comment

Exactly, In the first example it gets evaluated into separate words. In the second example it gets evaluated into one single word. - That is surprising and the reason for the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.