首页 > 解决方案 > 只有一个变量的 if 语句在 bash 中的计算结果是什么?

问题描述

我正在学习 bash --login 并看到其中的命令/etc/profile首先执行。在该文件中:

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "`id -u`" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

现在,我承认我对 bash 中的控制流了解有限,但据我了解,大多数情况下,我在 if 语句中看到的内容是某种条件语句,无论是[-a FILENAME]检查文件是否存在还是比较字符串,通常它评估为某事。

在文件中,两个 if 语句让我感到困惑:

if [ "$PS1" ];if[ "$BASH" ]

我知道 PS1 是主要提示的变量,但这就是 if 语句中的全部内容。它不使用 -a 来检查存在或将其与其他东西进行比较。我有根据的猜测是,如果变量存在,简单地放置一个变量就会评估为真。

我的问题是这些 if 语句的评估结果是什么,为什么?

标签: linuxbashshell

解决方案


[ "$var" ]如果 的长度$var不为零,则返回真。如果var未设置或为空,则返回 false。

这很有用:

  • [ "$PS1" ]仅对于交互式shell 将评估为 true。

  • [ "$BASH" ]只有当 shell 是 bash(与 dash、ksh 或 zsh 等相反)时才会评估为 true。

例子

只有以下一项评估为真:

$ unset x; [ "$x" ] && echo yes
$ x=""; [ "$x" ] && echo yes
$ x="a"; [ "$x" ] && echo yes
yes

文档

这在 bash 的交互式帮助系统中都有记录man bash,正如Glenn Jackman所指出的,在 bash 的交互式帮助系统中。有关该[命令的信息,请键入:

$ help [
[: [ arg... ]
    Evaluate conditional expression.

    This is a synonym for the "test" builtin, but the last argument must
    be a literal `]', to match the opening `['.

以上是指你test。运行help test以获取更多详细信息:

$ help test | less

滚动浏览该文档,发现:

  STRING      True if string is not empty.

推荐阅读