Reputation: 1457
how can we put a list in a for-loop in a shell script? I mean imagine that we have 1000 strings : string1.yaml ... string1000.yaml and we want to write a list LL={string1.yaml ... string1000.yaml} and say in the script:
for i in LL
do
...
done
specially it is a problem with the line breaking if one writes them simply one after another
for i in string1.yaml ... string1000.yaml
thanks a lot
Upvotes: 0
Views: 92
Reputation: 58768
If you have a massive amount of items you want to process, you probably want to put them in a separate file and read them like this:
$ cat strings.txt
string1.yaml
[...]
string1000.yaml
$ cat loop.sh
while IFS= read -r line
do
[...] "$line"
done < strings.txt
This way you avoid cluttering code with data, and the is POSIX compliant without being overly complex.
Upvotes: 0
Reputation: 530920
In POSIX shell, there's isn't really a good way. The naive approach:
LL="a b c d e"
for i in $LL; do
...
done
relies on the fact that no element in your list contains the delimiter (here, a space). If you know ahead of time what characters are not in your list, you can play with IFS
. For instance, if you know that no item will contain a comma, you could use
LL="a,b c,d,e" # Yes, the second item is "b c"
# This is not a perfect way to backup IFS; I'm ignoring the corner
# case of what happens if IFS is currently unset.
OLDIFS=$IFS
IFS=,
for i in $LL; do
...
done
IFS=$OLDIFS
If you are actually using bash
or another more modern shell, you can use an array, which was specifically introduced for this kind of problem. An array is essentially a second level of quoting, so you don't need to provide an explicit delimiter yourself.
LL=(a "b c" d e) # Four items, the second item contains a space
for i in "${LL[@}}"; do
...
done
Upvotes: 2