我正在学习 bash,我看到了这个结构:
cat file | while IFS= read -r line;
do
...
done
谁能解释一下是什么IFS=
?我知道它是输入字段分隔符,但为什么它被设置为空?
IFS
做了很多事情,但你问的是那个特定的循环。
该循环中的效果是保留line
. 为了说明,首先观察 IFS 设置为空:
$ echo " this is a test " | while IFS= read -r line; do echo "=$line=" ; done
= this is a test =
该line
变量包含它在其标准输入上收到的所有空白。现在,考虑使用默认 IFS 的相同语句:
$ echo " this is a test " | while read -r line; do echo "=$line=" ; done
=this is a test=
在这个版本中,行内部的空白仍然被保留。但是,前导和尾随空格已被删除。
-r
在做什么read -r
?该-r
选项可防止read
将反斜杠视为特殊字符。
为了说明,我们使用两个 echo 命令为while
循环提供两行。观察发生了什么-r
:
$ { echo 'this \\ line is \' ; echo 'continued'; } | while IFS= read -r line; do echo "=$line=" ; done
=this \\ line is \=
=continued=
现在,观察没有 会发生什么-r
:
$ { echo 'this \\ line is \' ; echo 'continued'; } | while IFS= read line; do echo "=$line=" ; done
=this \ line is continued=
没有-r
,发生了两个变化。首先,双反斜杠被转换为单反斜杠。其次,第一行末尾的反斜杠被解释为换行符,将两行合并为一个。
总之,如果您希望输入中的反斜杠具有特殊含义,请不要使用-r
. 如果您希望将输入中的反斜杠视为纯字符,请使用-r
.
由于read
一次输入一行,因此 IFS 的行为会影响多行输入的每一行,就像它影响单行输入一样。 -r
行为类似,不同之处在于,如果没有-r
,可以使用尾随反斜杠将多行组合成一行,如上所示。
然而,多行输入的行为可以使用 read 的-d
标志来彻底改变。 更改用于标记输入行结尾-d
的分隔符。read
例如,我们可以用制表符终止行:
$ echo $'line one \n line\t two \n line three\t ends here'
line one
line two
line three ends here
$ echo $'line one \n line\t two \n line three\t ends here' | while IFS= read -r -d$'\t' line; do echo "=$line=" ; done
=line one
line=
= two
line three=
在这里,该$'...'
构造用于输入特殊字符,例如换行符\n
和制表符\t
。观察到-d$'\t'
,read
根据制表符将其输入划分为“行”。最后一个选项卡之后的任何内容都将被忽略。
上述功能最重要的用途是处理难处理的文件名。由于路径/文件名中不能出现的一个字符是空字符,因此空字符可用于分隔文件名列表。举个例子:
while IFS= read -r -d $'\0' file
do
# do something to each file
done < <(find ~/music -type f -print0)