首页 > 解决方案 > 带有前置字符的 Bash if 语句

问题描述

我试图理解一个以root身份执行时将停止的脚本

#!/usr/bin/env bash

if [ x"$(whoami)" = x"root" ]; then
    echo "Error: don't run this script as root"
    exit 1
fi

我已经对此进行了测试,即使我x在 if 语句中删除了它,它也能按预期工作。我的问题是为什么xinx"$(whoami)"x"root"需要?

标签: bash

解决方案


basically the [ is a softlink to an external program called test, therefore the condition is passed to it as program arguments, and doing so if you don't surround a $variable with "$quotes" , and the variable happens to be empty it won't be considered as an empty argument, it will be considered as no argument (nothing)

#!/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

推荐阅读