shell 中 字符串比较 x”$variable”的使用
本文章参考stackoverflow上Why do shell script comparisons often use x$VAR = xyes?
- 不使用双引号“”,不使用前缀x
- 不使用双引号“”,使用前缀x
- 使用双引号“”,不使用前缀x
- 使用双引号“”,使用前缀x
不使用双引号“”,不使用前缀x
有变量SHELL_VAR未定义($SHELL_VAR为空)
if test $SHELL_VAR = yes; then --> if test = yes; then
显然是有语法错误的,test 丢失参数。
不使用双引号“”,使用前缀x
$SHELL_VAR值为空
if test x$SHELL_VAR = yes; then --> if test x = yes; then
这样貌似看着是没有问题的。
但是假如此时$SHELL_VAR值为” yes”,注意yes前面有一个空格,那么:
if test x$SHELL_VAR = yes; then --> if test x yes = yes; then
显然这样也是有语法错误的,test有两个参数x 和 1。
使用双引号“”,不使用前缀x
$SHELL_VAR值为空
if test "$SHELL_VAR" = "yes"; then --> if test "" = "yes"; then
$SHELL_VAR值为” yes”
if test "$SHELL_VAR" = "yes"; then --> if test " yes" = "yes"; then
貌似使用“”把变量包起来就没有问题了。
但是假如此时$SHELL_VAR值为“-n”或者 “-f”
if test "$SHELL_VAR" = "yes"; then --> if test "-f" = "yes"; then
那么此时“-f” 是有二义性的,是作为test命令的option还是test的argument。
使用双引号“”,使用前缀x
$SHELL_VAR值为空
if test x"$SHELL_VAR" = x"yes"; then --> if test x"" = x"yes"; then
$SHELL_VAR值为” yes”
if test x"$SHELL_VAR" = x"yes"; then --> if test x" yes" = x"yes"; then
$SHELL_VAR值为“-n”或者 “-f”
if test x"$SHELL_VAR" = x"yes"; then --> if test x"-f" = x"yes"; then