个性化阅读
专注于IT技术分析

bash检查变量是否已设置

变量通常称为包含名称和内容的框。一个简单的命令,例如,“ echo Hello $ Var_Name”将显示“ Hello …所定义变量的值”。如果该框为空或未创建,则Bash将不打印任何内容。这就是为什么在创建任何bash脚本时确保变量是否正确设置的重要性。

变量可以分为两部分:

  • 定义变量正确创建或初始化的变量称为定义变量。它们可能具有零值或空字符串。
  • 未定义变量从未创建或初始化的变量称为未定义变量。

为了确认在Bash脚本中是否设置了变量,我们可以使用-v var或-z $ {var}选项作为表达式与’if’条件命令的组合。

句法

以下是布尔表达式的语法,可用于检查是否设置了变量:

[[ -v Variable_Name ]]

[[ -z Variable_Name ]]

如果设置了变量,则布尔表达式返回“ True”,如果未设置则返回“ False”。

以下是检查是否设置了变量的示例:

使用-v选项

#!/bin/bash
#Script to check whether a variable is set or not using -v option

A=100
#A: variable is set.

if [[ -v A ]];
then
echo "Variable having name 'A' is already set."
else
echo "Variable having name 'A' is not set."
fi

#B: variable is not set
if [[ -v B ]];
then
echo "Variable having name 'B' is already set."
else
echo "Variable having name 'B' is not set."
fi

输出量

在此,变量“ A”被定义并分配为100,因此被视为“设置变量”。对于变量“ B”,我们尚未定义或分配任何值。结果,变量“ B”不被视为“设置变量”。

使用-z选项

#!/bin/bash
#Script to check whether a variable is set or not using -z option

A=100
#A: variable is set.
if [[ -z ${A} ]];
then
echo "Variable having name 'A' is not set."
else
echo "Variable having name 'A' is already set."
fi

#B: variable is not set
if [[ -z ${B} ]];
then
echo "Variable having name 'B' is not set."
else
echo "Variable having name 'B' is already set."
fi

输出量

注意:未设置的变量和具有空值的变量之间存在区别。

请查看以下示例,该示例说明具有空值的变量可以是set变量。

VAR=''

#VAR is set

if [ -z ${VAR+x} ]; 
then 
echo "'VAR' is unset"; 
else 
echo "'VAR' is set, its content is '$VAR'"; 
fi

#Var is not set
if [ -z ${Var+x} ]; 
then 
echo "'Var' is unset"; 
else 
echo "'Var' is set, its content is '$Var'"; 
fi

输出量

这些是可用于检查是否设置了变量的常用方法。


赞(0)
未经允许不得转载:srcmini » bash检查变量是否已设置

评论 抢沙发

评论前必须登录!