【发布时间】:2013-10-12 00:39:00
【问题描述】:
我正在尝试在 shell 中使用 for 来迭代带有空格的文件名。我在stackoverflow question 中读到IFS=$'\n' 可以使用,而且似乎工作正常。然后我读到in a comment to one of the answers,为了使它与bash 以外的shell 兼容,可以使用IFS=$(echo -e '\n')。
前者有效,后者无效。这条评论被点赞了好几次。我检查了输出,变量似乎不包含换行符。
#!/bin/sh
IFS=$(echo -e '\n')
echo -n "$IFS" | od -t x1
for file in `printf 'one\ntwo two\nthree'`; do
echo "Found $file"
done
echo
IFS=$'\n'
echo -n "$IFS" | od -t x1
for file in `printf 'one\ntwo two\nthree'`; do
echo "Found $file"
done
输出显示第一个字段分隔符缺失:
0000000
Found one
two two
three
但是第二个是正确的:
0000000 0a
0000001
Found one
Found two two
Found three
我找到了一个已回答的问题,它可能与我的问题重复也可能不重复:
linux - When setting IFS to split on newlines, why is it necessary to include a backspace? - Stack Overflow
做那里讨论的事情有什么危险吗,IFS=$(echo -en '\n\b')?因为这会在 IFS 中添加一个\b(我检查过)。 \b 可以出现在文件名中吗?我不希望我的代码错误地拆分文件名。
对于如何在for 循环后正确处理 IFS 恢复,您有什么建议吗?我应该将它存储在临时变量中,还是在子shell 中运行 IFS 和 for 语句? (以及如何做到这一点?)谢谢
【问题讨论】: