检查是否在 Bash 中设置了变量
Nilesh Katuwal
2023年1月30日
Bash
Bash Variable
我们必须首先定义一个变量并给它一个值来设置一个变量。
该值可以为空,但必须赋值。未设置变量和空变量之间存在区别。
与大多数常见的编程语言不同,Bash 没有用于确定是否设置变量的内置函数。尽管如此,它确实有能力这样做。
在 Bash 脚本中,我们可以使用 -v var 或 -z $var 选项作为带有 if 条件命令的表达式来确认是否设置了变量。
[[-v Name_Of_Variable]]
[[-z Name_Of_Variable]]
如果设置了变量,则布尔表达式返回 True,否则返回 False。
在 Bash 中检查是否使用 -v 设置了变量
我们现在将检查是否使用 -v 变量设置了变量。
让我们定义一个值为 5 的变量 X。如果变量已设置,它将返回变量'X'已设置。。
#!/bin/bash
X=5
if [[ -v X ]];
then
echo "Variable 'X' is set."
else
echo "Variable 'X' is not set."
fi
输出:
Variable 'X' is set.
由于我们定义了变量并分配了值,因此它按预期工作。让我们看另一个例子。
#!/bin/bash
if [[ -v Y ]];
then
echo "Variable 'Y' is set."
else
echo "Variable 'Y' is not set."
fi
输出:
Variable 'Y' is not set.
由于我们没有定义任何变量 Y,输出显示变量 Y 未设置。
在 Bash 中检查是否使用 -z 设置了变量
我们现在将检查是否使用 -z Variable 设置了变量。
让我们定义一个值为 5 的变量 X。如果变量已设置,它将返回 Variable 'X' is set.。
#!/bin/bash
X=5
if [[ -z ${X} ]];
then
echo "Variable 'X' is not set."
else
echo "Variable 'X' is set."
fi
在这里,第一个 if 条件将返回 False,第二个将返回 True,Variable 'X' is set. 将打印。
输出:
Variable 'X' is set.
它按预期工作,因为我们定义了变量并为其分配了一个值。考虑另一个例子。
#!/bin/bash
if [[ -z ${X} ]];
then
echo "Variable 'X' is not set."
else
echo "Variable 'X' is set."
fi
输出:
Variable 'X' is not set.
在 Bash 中通过分配空值来检查是否设置了变量
我们现在将检查是否使用 -v Variable 设置了变量。
让我们定义一个具有 null 值的变量 X 作为 X=""。如果变量已设置,它将返回 Variable 'X' is set.。
#!/bin/bash
X=""
if [[ -v X ]]; then
echo "Variable 'X' is set."
else
echo "Variable 'X' is not set."
fi
输出:
Variable 'X' is set.
正如我们所看到的,即使将一个 null 值分配给一个变量,它也会在检查后显示为 set。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe