bash loop through list of strings
Using arrays in bash can aid readability: this array syntax allows arbitrary whitespace between words.
strings=(
string1
string2
"string with spaces"
stringN
)
for i in "${strings[@]}"; do
echo "$i"
done
You can escape the linebreak with a backslash:
$ for i in \
> hello \
> world
> do
> echo $i
> done
hello
world
$
You may escape the newlines before/after each item that you loop over:
for i in \
string1 \
string2 \
stringN
do
printf '%s\n' "$i"
done
Or, for this simple example:
printf '%s\n' string1 string2 stringN
which has the same result.
Related:
- Why do I need to place “do” in the same line as “for”?
Variation using a bash
array:
strings=(
string1
string2
stringN
)
printf '%s\n' "${strings[@]}"