我的脚本非常简单:
$ cat $$.sh
#!/bin/sh -x
VAR="one two
three four"
for i in $VAR ; do
echo $i
done
$
运行输出:
$ sh -x $$.sh
+ VAR='one two
three four'
+ for i in '$VAR'
+ echo one
one
+ for i in '$VAR'
+ echo two
two
+ for i in '$VAR'
+ echo three
three
+ for i in '$VAR'
+ echo four
four
$
似乎正在寻找一个空间,我需要它来寻找换行符
答案 0 :(得分:5)
如果您逐行读取多行,则while read
循环是执行此操作的常用方法:
VAR="one two
three four"
while IFS='' read -r i ; do
echo "$i"
done <<< "$VAR"
这会产生:
one two three four
请注意,在此示例中,while循环使用bash here-string redirection从$VAR
变量获取输入。但这可以很容易地从文件或管道重定向。
答案 1 :(得分:2)
默认情况下,shell会在空格和换行符上执行分词。请将IFS
设置为换行符。此外,如果您使用for
,那么最好关闭通配(按照@CharlesDuffy的建议):
set -o noglob
VAR="one two
three four"
IFS=$'\n'
for i in $VAR ; do
echo $i
done
这会产生:
one two
three four