Dave Halter
Dave Halter

Reputation: 16325

Shell: Write for ... in arguments into a variable

for i in "a" "a b"; do
    echo $i;
done

echoes:

a
a b

How can I write something like for i in $input; do and assign "a" "a b" to input? The whitespace is important. Otherwise $(echo ...) would work.

Edit: The question is not about files and neither about some input, which can be caught using $@.

Upvotes: 0

Views: 126

Answers (2)

zwol
zwol

Reputation: 140579

This can only be done portably with the "$@" construct for command-line arguments.

However, if you don't need the actual command line arguments anymore, you can use set to replace their contents:

input='"a" "a b"'
eval set fnord $input
shift
for i in "$@"; do
    echo $i
done

You should be aware that merely having asked this question suggests that you are approaching the complexity level where you should switch to a less limited scripting language (Perl and Python are the usual choices).

Upvotes: 1

Tim Pote
Tim Pote

Reputation: 28029

Since you're using bash, you could do this:

input=("a" "a b")

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

Upvotes: 4

Related Questions