$ A=B C # 空白键未被关闭,作为IFS 处理。
$ C: command not found.
$ echo $A
$ A="B C" # 空白键已被关闭,仅作空白符号处理。
$ echo $A
B C
在第一次设定 A 变量时,由于空白键没有被关闭,command line 将被解读为:
* A=B 然后碰到<IFS>,再执行 C 命令
在第二次设定 A 变量时,由于空白键置于 soft quote 中,因此被关闭,不再作为 IFS :
* A=B<space>C
事实上,空白键无论在 soft quote 还是在 hard quote 中,均会被关闭。Enter 鍵亦然:
$ A='B
> C
> '
$ echo "$A"
B
C
在上例中,由于 <enter> 被置于 hard quote 当中,因此不再作为 CR 字符來处理。
这里的 <enter> 单纯只是一个断行符号(new-line)而已,由于 command line 并沒得到 CR 字符,
因此进入第二個 shell prompt (PS2,以 > 符号表示),command line 并不会结束,
直到第三行,我们输入的 <enter> 并不在 hard quote 里面,因此并沒被关闭,
此时,command line 碰到 CR 字符,于是结束、交给 shell 來处理。
上例的 <enter> 要是被置于 soft quote 中的话, CR 也会同样被关闭:
$ A="B
> C
> "
$ echo $A
B C
然而,由于 echo $A 时的变量沒置于 soft quote 中,因此当变量替换完成后并作命令行重组时,<enter> 会被解释为 IFS ,而不是解释为 New Line 字符。
[iyunv@jasontest01 ~]# awk '{print $0}' 1.txt #而这里因为有''作用,所以$0其实是由awk程序解释
i am student
my teacher is oldboy
i am very happy
i come from guangzhou
now i am in beijing
上面的 hard quote 应好理解,就是將原本的 {、<space>、$(注三)、} 这几个 shell meta 关闭,
避免掉在 shell 中遭到处理,而完整的成为 awk 参数中的 command meta 。
( 注三:而其中的 $0 是 awk 內建的 field number ,而非 awk 的变量,
awk 自身的变量无需使用 $ 。)
要是理解了 hard quote 的功能,再來理解 soft quote 与 escape 就不难:
[iyunv@jasontest01 ~]# awk "{print \$0}" 1.txt
i am student
my teacher is oldboy
i am very happy
i come from guangzhou
now i am in beijing
[iyunv@jasontest01 ~]# awk \{print\ \$0\} 1.txt
i am student
my teacher is oldboy
i am very happy
i come from guangzhou
now i am in beijing
debian:~/learn/shell# cat phonebook
Alice Chebba 973-555-2015
Barbara Swingle 201-555-9257
Liz Stachiw 212-555-2298
Susan Goldberg 201-555-7776
Susan Topple 212-555-4932
Tony Iannino 973-555-1295
Stromboli Pizza 973-555-9478
debian:~/learn/shell#
debian:~/learn/shell# cat lu
# Look someone up in the phone book
grep "$1" phonebook
debian:~/learn/shell#
这是正确的lu程序,下面是运行结果。
debian:~/learn/shell# ./lu 'Susan T'
Susan Topple 212-555-4932
debian:~/learn/shell# ./lu Tony
Tony Iannino 973-555-1295
debian:~/learn/shell#