Bash教程

Bash 检查设置变量

Bash 检查是否设置了变量

变量通常被称为包含名称和内容的框。一个简单的命令,例如,"echo Hello $Var_Name"将打印"Hello...定义的变量值"。如果框为空或未创建,Bash 将不打印任何内容。这就是为什么在创建任何 bash 脚本时确保变量设置是否正确很重要。
变量可以分为两部分:
定义变量
正确创建或初始化的变量称为定义变量。这些可能有零值或空字符串。
未定义变量
从未创建或初始化的变量称为未定义变量。
要确认在 Bash Scripting 中是否设置了一个变量,我们可以使用 -v var 或-z ${var} 选项作为组合'if ' 条件命令。

语法

以下是布尔表达式的语法,可用于检查变量是否已设置:
[[-v Variable_Name ]]
[[-z Variable_Name ]]
布尔表达式在设置变量时返回'True',如果未设置变量则返回'False'。
以下是检查变量是否设置的示例:
p>

使用-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
输出
Bash 检查变量是否为Set
这里,变量"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
输出
Bash 检查变量是否为设置
注意: 未设置变量和具有空值的变量是有区别的。
查看下面的示例,演示具有空值的变量可以是设置变量。

示例

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
输出
Bash 检查变量是否为Set
这些是常用的方法,可以用来检查变量是否被设置。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4