shell 中 test ([])比较字符串 x"$variable"的使用

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

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值