【发布时间】:2021-08-22 04:10:30
【问题描述】:
我有以下代码:
script_list=$'1 a\n2\n3'
old_IFS="${IFS}"
IFS=$'\n'
for line in "${script_list}"; do
echo "__${line}__";
done
IFS="${old_IFS}"
应该产生:
__1 a__
__2__
__3__
然而,它却给了我:
__1 a
2
3__
我双引号 "${script_list}" 因为它可以包含空格(请参阅:https://stackoverflow.com/a/10067297)。但我相信这也是问题所在,因为当我删除它周围的双引号时,它会按预期工作。
我错过了什么?
编辑: 正如 Cyrus 建议的那样,我在 ShellCheck 上运行了代码,它告诉我:
$ shellcheck myscript
Line 5:
for line in "${script_list}"; do
^-- SC2066: Since you double quoted this, it will not word split, and the loop will only run once.
简单地删除双引号是否安全,还是我需要小心?
【问题讨论】:
-
你问
Why is my line read not working as expected in bash?所以你有答案Since you double quoted this, it will not word split, and the loop will only run once。 ||Is it safe to simply remove the double quotes or do I need to be careful with that?定义“安全”。它将是“安全的”,因为循环将执行。但请注意文件名扩展。 ||你是在问 XY 问题吗? -
只要 script_list 不包含通配符,它就是安全的。但我不知道你在那里做什么。你为什么需要这个?有什么意义?