gpt4 book ai didi

linux - bash 中只有一个变量的 if 语句的计算结果是什么?

转载 作者:太空狗 更新时间:2023-10-29 11:40:31 24 4
gpt4 key购买 nike

我正在学习 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 语句的计算结果是什么,为什么?

最佳答案

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

这很有用:

  • [ "$PS1"] 仅对交互式 shell 求值为真。

  • [ "$BASH"] 仅当 shell 为 bash(与 dash、ksh 或 zsh 等相反)时才会计算为真。

    <

例子

只有以下一项的计算结果为真:

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

文档

这在 man bashGlenn 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.

关于linux - bash 中只有一个变量的 if 语句的计算结果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699956/

24 4 0
文章推荐: css - rails : Alternative for bootstrap select?
文章推荐: html - 带 CSS/HTML 的页码
文章推荐: html - 可滚动?