IFS在Bash中如何工作? [英] How does IFS work in Bash?
问题描述
#!/bin/bash
# This question is from advanced bash scripting guide section 5.1
echo
var="'(]\\{}\$\""
IFS='\'
echo $var
# output is '(] {}$"
# \ converted to space. Why?
echo "$var"
# output is '(]\{}$"
# special meaning of \ used, \ escapes \ $ and " RIGHT?
echo
var2="\\\\\""
echo $var2
# output is "
# \ converted to space. Why?
echo
# But ... var2="\\\\"" is illegal. Why?
var3='\\\\'
echo "$var3" # \\\\
# Strong quoting works, though. Why?
推荐答案
IFS='\'
echo $var
# o/p is '(] {}$"
# \ converted to space. Why?
因为您告诉Shell反斜杠是字段分隔符,并且由于在回显时没有引用$var
,所以必须遵守
Because you told the shell that a backslash is a field separator and since you did not quote $var
when you echo'd it out, it was subject to word splitting based on IFS.
echo "$var"
# o/p is '(]\{}$"
# special meaning of \ used, \ escapes \ $ and " RIGHT ?
在这里引用了$var
,因此不会对其执行分词.您的输出正是您告诉shell var
等于的内容.即'(]\{}$"
Here you quoted $var
and thus no word splitting will be performed on it. Your output is exactly what you told the shell var
was equal to. i.e. '(]\{}$"
var2="\\\\\""
echo $var2
# o/p is "
# \ converted to space. Why?
查看第一个答案
# But ... var2="\\\\"" is illegal. Why?
因为每对反斜杠都构成一个文字上的反斜杠,并且没有多余的反斜杠用于转义第二个双引号.外壳不知道如何用3个双引号引起来.
Because every pair of backslashes makes up a literal backslash and there is no backslash left over to escape out the 2nd double quote. The shell doesn't know what to do with 3 double quotes.
echo "$var3" # \\\\
# Strong quoting works, though. Why ?
请参阅有关分词的第二个答案
注意,您还可以使用字符串文字语法$''
相对于var=$'\'(]\{}$"'
,该语法仅要求您转义单引号
Note that you could also use the string literal syntax $''
vis var=$'\'(]\{}$"'
which would only require you to escape out the single quote
这篇关于IFS在Bash中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!