#!/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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
IFS='\' echo $var # o/p is '(] {}$" # \ converted to space. Why?
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 ?
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?
See first answer
# But ... var2="\\\\"" is illegal. Why?
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 ?
See second answer about word splitting
Note that you could also use the string literal syntax $''
vis var=$'\'(]\{}$"'
which would only require you to escape out the single quote