0

At some point in my script I need to save value of all command line arguments in a variable (after some shifting), it looks like this:

foo="$@"

Now I need to interate through the arguments from foo variable, but it seems to be quite hard to do it properly if there are arguments containing write space. If I write

for i in "$foo"
do
    echo "$i"
done

Everything is printed on one line, indicating that for thinks there is only one argument. On the other hand:

for i in $foo
do
    echo "$i"
done

seems to do the right thing, but it fails too when there are arguments containing write space:

$ my_script one two "three four"
one
two
three
four

In this example three and four should be printed on the same line.

How to iterate though arguments saved in a variable properly?

1

1 Answer 1

2

You could use bash arrays:

foo=("$@")

for i in "${foo[@]}"; do
    echo "$i"
done

This also allows you to address individual arguments as ${foo[0]}, ${foo[1]}, and so forth, up to ${#foo[@]}, which is the length of the array.

Note that arrays are bash-specific (not part of the POSIX shell language).

Sign up to request clarification or add additional context in comments.

4 Comments

Great. The only problem is that it's bash specific. But it's not critical for me. Thanks!
@Mark, you tagged your question with bash, so don't be surprised to get bash answers.
@glennjackman, good point. Next time I will tag it with [shell] too ;-)
@Mark The implementation of something vaguely array-ish in POSIX shell that is not painful to both write and to use is, as far as I'm aware, an unsolved problem. It'll generally involve something like eval set -- "$array" to expand the array into the positional variables, and doing that requires meticulous quoting with special care given to single quotes within the arguments. If you find yourself in a position where you need it and can't rely on bash, consider using another programming language. Perl comes to mind -- boxes that don't have it are few and far between these days.

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.