linux - 只有一个变量的 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 语句的评估结果是什么,为什么?
解决方案
[ "$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.
推荐阅读
- java - 如何使用键作为字符串读取多维 HashMap
- swift - 查看模型组合打破了 mvvm 结构
- qliksense - 数据透视表,每列都从其中扣除前列值
- python-3.x - 如何链接散景布局中所有绘图的轴?
- node.js - 更改 GruntFile 不会更改 livereload 端口
- java - Solr ClassCastException 与自定义 TokenFilterFactory
- android - 如何以编程方式从 android 设备导入和读取随机 SQLITE 数据库文件 (.db)?
- java - 如何在 Jmeter 中发送 http 表单
- angular - 业力并行 npm 包不适用于圆形 CI
- azure-devops - 尝试从 Azure Dev Ops 创建燃尽图到 Power Bi 时使用哪些字段和计算