0

This question already has an answer here:

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

marked as duplicate by user88036, RalfFriedl, steve, Thomas, Archemar Sep 23 '18 at 16:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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:

  • The code works even thought there is no IFS=' '. Is that needed? – Jim Sep 22 '18 at 16:34
  • @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: 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 the set -f? Which I think corrects the problem of not using quotes – Jim Sep 22 '18 at 19:25

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