Bash arrays are, in fact, arrays. They are not strings which are parsed on demand. Once you create an array, the elements are whatever they are, and they won't change retroactively.
However, nothing in your example creates an array. If you wanted to create an array out of argument 2, you would need to use a different syntax:
strings_to_find=($2)
Although your strings_to_find
is not an array, bash allows you to refer to it as though it were an array of one element. So ${#strings_to_find[@]}
will always be one, regardless of the contents of strings_to_find
. Also, your line:
for string in ${strings_to_find[@]}
is really no different from
for string in $strings_to_find
Since that expansion is not quoted, it will be word-split, using the current value of IFS
.
If you use an array, most of the time you will not want to write for string in ${strings_to_find[@]}
, because that just reassembles the elements of an array into a string and then word-splits them again, which loses the original array structure. Normally you will avoid the word-splitting by using double quotes:
strings_to_find=(...)
for string in "${strings_to_find[@]}"
As for your second question, the value of IFS
does not alter the shell grammar. Regardless of the value of IFS
, words in a command are separated by unquoted whitespace. After the line is parsed, the shell performs parameter and other expansions on each word. As mentioned above, if the expansion is not quoted, the expanded text is then word-split using the value of IFS
.
If the word does not contain any expansions, no word-splitting is performed. And even if the word does contain expansions, word-splitting is only performed on the expansion itself. So, if you write:
IFS=:
my_function a:b:c
my_function
will be called with a single argument; no expansion takes places, so no word-splitting occurs. However, if you use $1
unquoted inside the function, the expansion of $1
will be word-split (if it is expanded in a context in which word-splitting occurs).
On the other hand,
IFS=:
args=a:b:c
my_function $args
will cause my_function
to be invoked with three arguments.
And finally,
IFS=:
args=c
my_function a:b:$args
is exactly the same as the first invocation, because there is no :
in the expansion.