更新#2
解释在Blue Moons的答案中。
替代方案:
消除echo
。
while read line; do
...
done <<EOT
first line
second line
third line
EOT
在这里是文档内部添加回显。
while read line; do
...
done <<EOT
$(echo -e $lines)
EOT
在后台运行echo
命令:
coproc echo -e $lines
while read -u ${COPROC[0]} line; do
...
done
显式地将重定向到文件句柄(注意在<<
中的空格!):
exec 3< <(echo -e $lines)
while read -u 3 line; do
...
done
或者直接重定向到 stdin
:
while read line; do
...
done < <(echo -e $lines)
还有一种方法专门为chepner
设计的(消除echo
):
arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]};
...
}
变量$lines
可以在不启动新的子 shell 的情况下转换为数组。 需要将字符\
和n
转换为一些字符(例如真实的新行字符),并使用IFS(内部字段分隔符)变量将字符串拆分为数组元素。 可以这样做:
lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'})
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr
结果为
first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")
SC2030: Modification of foo is local (to subshell caused by pipeline).
- qneill