【问题标题】:Bash if statement with prepended character [duplicate]带有前置字符的 Bash if 语句 [重复]
【发布时间】:2019-04-27 11:34:31
【问题描述】:

我正在尝试理解一个script,它会在以 root 身份执行时停止:

#!/usr/bin/env bash

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

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

【问题讨论】:

  • 这个构造中的x 是一个古老的习惯用法,用于解决某些shell 中无法正确处理空字符串的错误。在现代 shell 中通常不需要它。
  • 你使用的是什么版本?
  • @bluerojo bash 版本 4.3.48(1)。我意识到脚本在没有x 的情况下也可以工作。我已经编辑了问题。
  • @Sergio 如果它在没有 x 的情况下工作,那么我对这个问题感到困惑?

标签: bash


【解决方案1】:

基本上 [ 是指向名为 test 的外部程序的软链接,因此条件作为程序参数传递给它,并且如果您不使用 "$quotes" 包围 $variable 并且变量恰好是为空它不会被视为空参数,它将被视为无参数(无)

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

【讨论】:

  • 在 Bash 中,[ 是内置程序,而不是外部程序。
  • 同意[,但除此之外,这是一篇极好的早期帖子。您展示所有可能性是“插图解释代码”(恕我直言)的一个很好的例子,继续发帖!祝大家好运。
猜你喜欢
  • 2019-08-20
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
相关资源
最近更新 更多