#!/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?
问问题
2646 次
1 回答
3
IFS='\' echo $var # o/p is '(] {}$" # \ converted to space. Why?
因为您告诉 shell 反斜杠是字段分隔符,并且由于您在回显时没有引用$var
,所以它会根据 IFS进行分词。
echo "$var" # o/p is '(]\{}$" # special meaning of \ used, \ escapes \ $ and " RIGHT ?
您在这里引用$var
,因此不会对其执行分词。您的输出正是您告诉 shell 的var
结果。IE'(]\{}$"
var2="\\\\\"" echo $var2 # o/p is " # \ converted to space. Why?
看第一个答案
# But ... var2="\\\\"" is illegal. Why?
因为每对反斜杠都构成一个文字反斜杠,并且没有剩余的反斜杠可以逃脱第二个双引号。shell 不知道如何处理 3 个双引号。
echo "$var3" # \\\\ # Strong quoting works, though. Why ?
请参阅有关分词的第二个答案
请注意,您还可以使用字符串文字语法$''
vis var=$'\'(]\{}$"'
,它只需要您转义单引号
于 2011-03-30T22:48:12.957 回答