0

I am wondering why the following 2 cases have two different outputs. I expected 2 on the second case:

localhost:~$ titles=('word1  word2' 'word1  word2')
localhost:~$ echo "${#titles[@]}"
2

localhost:~$ titles=($(echo "'word1  word2' 'word1  word2'"))
localhost:~$ echo "${#titles[@]}"
4
1

1 Answer 1

3

The first assignment to the array titles assigns the two strings word1  word2 and word1  word2 to the array.

The second assignment contains an unquoted command substitution. The command in the substitution outputs the single string 'word1  word2' 'word1  word2', and, since the substitution is unquoted, the shell will split this string on the characters in $IFS into words (by default, this variable contains a space, a tab, and a newline).

When the string is split into words, the words generated are 'word1, word2', 'word1 and word2' (four words). These words are then assigned as individual elements to the array titles.

This is further explained in the answers to other questions. See for example:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.