I have a function that one of the arguments is an string that has space separated words.
E.g. "foo bar ccc"
I think this kind of string can be treated as an "array" and loop over each word.
My question is if I need to pass this as an argument to a function can it be the first argument or will it create issues?
I tried it as a first argument and it works but I am not sure if there are any pitfalls I need to watch out
Asked
Active
Viewed 167 times
0

Jim
- 1,391
-
As long as the first argument is carfully quoted, it can contain spaces, and it should not be a problem. – Alexander Sep 23 '18 at 09:12
1 Answers
1
That's a string, not a real array. But yes, you can pass a string with spaces to a function, either as the first argument, or as any other.
set -f
f() {
IFS=' '
for x in $2; do echo "> $x"; done
}
liststr="foo bar ccc"
f something "$liststr" somethingelse
Remember that if you use an unquoted expansion to split the string, the resulting words will also go through globbing, which may or may not be what you want. You can disable globbing (globally) with set -f
, as above.
But since you tagged this with Bash, you should probably use a proper array instead and then either pass the array name to use with a nameref variable, or just split the array to separate arguments when calling the function.
See:

ilkkachu
- 138,973
-
-
@Jim, if
IFS
is set to the default (space, tab and newline), then yeah, it works to split on spaces. – ilkkachu Sep 22 '18 at 16:42 -
When you say "unquoted expansion to split the string" you mean
$2
vs"$2"
? And what do you mean by "globbling"? Could you please elaborate on an example of how it could mess up what I am trying to do? – Jim Sep 22 '18 at 18:17 -
1@Jim, see the "what happens without quotes" part here: https://unix.stackexchange.com/a/131767/170373 . Without the
set -f
, something like `liststr="foo * ccc" in the above would run the loop over all files in the current directory. – ilkkachu Sep 22 '18 at 18:43 -
I see... but then I should always use double quotes. Why would I do
$2
? Or are you just giving all possible pitfalls? E.g. in case I don't use double quotes I should not forget theset -f
? Which I think corrects the problem of not using quotes – Jim Sep 22 '18 at 19:25 -
@Jim, you need to expand it unquoted to split the words. Or use something like
read -a array <<< "$2"
, but then you might as well use a proper array to begin with. – ilkkachu Sep 23 '18 at 11:47