IFS=$' ' 的确切含义是什么? [英] What is the exact meaning of IFS=$' '?
问题描述
如果以下示例将 IFS
环境变量设置为换行符...
If the following example, which sets the IFS
environment variable to a line feed character...
IFS=$'
'
- 美元符号是什么意思正是?
- 它在这个具体做什么案例?
- 在哪里可以阅读有关此特定用法的更多信息(Google 不允许在搜索中使用特殊字符,否则我不知道要查找什么)?
我知道 IFS
环境变量是什么,以及
字符是什么(换行),但为什么不直接使用以下形式:IFS="
"
(不起作用)?
I know what the IFS
environment variable is, and what the
character is (line feed), but why not just use the following form:
IFS="
"
(which does not work)?
例如,如果我想遍历文件的每一行并想使用 for 循环,我可以这样做:
For example, if I want to loop through every line of a file and want to use a for loop, I could do this:
for line in (< /path/to/file); do
echo "Line: $line"
done
但是,除非将 IFS
设置为换行符,否则这将无法正常工作.为了让它工作,我必须这样做:
However, this won't work right unless IFS
is set to a line feed character. To get it to work, I'd have to do this:
OLDIFS=$IFS
IFS=$'
'
for line in (< /path/to/file); do
echo "Line: $line"
done
IFS=$OLDIFS
注意:我不需要另一种方式来做同样的事情,我已经知道很多其他的......我只是对那个$'
'
感到好奇代码>并想知道是否有人可以给我一个解释.
Note: I don't need another way for doing the same thing, I know many other already... I'm only curious about that $'
'
and wondered if anyone could give me an explanation on it.
推荐答案
通常 bash
不解释字符串文字中的转义序列.因此,如果您编写
或 "
"
或 '
'
,那不是换行符 - 它是字母 n
(在第一种情况下)或反斜杠后跟字母 n
(在其他两种情况下).
Normally bash
doesn't interpret escape sequences in string literals. So if you write
or "
"
or '
'
, that's not a linebreak - it's the letter n
(in the first case) or a backslash followed by the letter n
(in the other two cases).
$'somestring'
是带有转义序列的字符串文字的语法.所以与 '
'
不同,$'
'
实际上是一个换行符.
$'somestring'
is a syntax for string literals with escape sequences. So unlike '
'
, $'
'
actually is a linebreak.
这篇关于IFS=$' ' 的确切含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!