IFS 在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您告诉 shell 反斜杠是字段分隔符,并且在 echo 出它时没有引用
$var
,所以它受到 基于 IFS 的分词。在这里,您引用了
$ var
,因此no word拆分将在上面执行。您的输出正是您告诉 shellvar
的内容。即'(] \ {} $“
请参阅第一个答案
因为每对后斜线都构成了字面的后斜线,并且没有剩下的后斜线来逃脱第二个双引号。外壳不知道该如何处理3个双引号。
有关
请参阅
$''
与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.Here you quoted
$var
and thus no word splitting will be performed on it. Your output is exactly what you told the shellvar
was equal to. i.e.'(]\{}$"
See first answer
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.
See second answer about word splitting
Note that you could also use the string literal syntax
$''
visvar=$'\'(]\{}$"'
which would only require you to escape out the single quote