代码之家  ›  专栏  ›  技术社区  ›  builder-7000

带前置字符的bash if语句[重复]

  •  2
  • builder-7000  · 技术社区  · 6 年前

    我在试着理解 script 当以根用户身份执行时将停止:

    #!/usr/bin/env bash
    
    if [ x"$(whoami)" = x"root" ]; then
        echo "Error: don't run this script as root"
        exit 1
    fi
    

    我已经测试过了,即使我移除了 x 在if语句中。我的问题是为什么 X 在里面 x"$(whoami)" x"root" 需要?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Imre    6 年前

    基本上,[是指向名为test的外部程序的软链接,因此条件作为程序参数传递给它,如果不将$variable用“$quotes”括起来,并且变量恰好为空,则不会将其视为空参数,而是将其视为没有争论(没有)

    #!/bin/bash -eu
    
    var=bla
    
    if [[ $var == bla ]];then
      echo first test ok
    fi
    
    var=""
    
    if [[ $var == "" ]];then
      echo second test ok
    fi
    
    if [ "$var" == "" ];then
      echo third test ok
    fi
    
    if [ x$var == "x" ];then
      echo fourth test ok
    fi
    
    echo this will fail:
    
    if [ $var == "" ];then
      echo fifth test ok
    fi
    
    echo because it is the same as writing:
    
    if [ == "" ];then
      echo sixth test is obviously eroneous
    fi
    
    echo but also you should quote your variables because this will work:
    
    var="a b"
    
    if [ "$var" == "a b" ];then
      echo seventh test ok
    fi
    
    echo ... but this one won\'t as test now has four arguments:
    if [ $var == "a b" ];then
      echo eighth test ok
    fi