Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

bash - Loop over set of strings containing spaces

I have multiple strings like "a b", "c d", "foo bar" and so on. I want to loop over this set of string and perform an action on each of these. In this action I call multiple other scripts so I do not want to change IFS for this loop since it could break my invocation of other scripts. This is why I try to escape the spaces contained in these strings but without success.

So for instance I expect to get

a b
c d

And I tried the following:

#!/bin/sh

x="a b"
y="c d"

echo "Attempt 1"
all="$x $y"

for i in $all ; do
  echo $i
done

echo "Attempt 2"
all="a b c d"
for i in $all ; do
  echo $i
done

echo "Attempt 3"
all=($x $y)
for i in ${all[@]} ; do
  echo $i
done

echo "Attempt 4"
all='"'$x'" "'$y'"'
for i in $all ; do
  echo $i
done

echo "Attempt 5"
for i in "$x" "$y" ; do
  echo $i
done

echo "Attempt 6"
all2=("a b" "c d");
for i in ${all2[@]}; do
  echo $i
done

echo "Attempt 7"
all3="a b c d"
echo $all3|
while read i; do
  echo $i 
done 

Only attempt 5 succeeds, but I would like to do this without having to declare one variable per string, (it would be painful to maintain). I just introduced x and y for testing but the idea is to declare in one variable the set "a b" and "c d".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to wrap variables within double quotes, both in all=("$x" "$y") and "${all[@]}":

x="a b"
y="c d"

echo "Attempt XX"
all=("$x" "$y")
for i in "${all[@]}" ; do
  echo "$i"
done

Executing it returns:

Attempt XX
a b
c d

Update

To avoid using a different variable for each string, do the following:

all=("a b" "c d")
for i in "${all[@]}" ; do
  echo "$i"
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...