我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
当前回答
要查看变量是否为非空,我使用
if [[ $var ]]; then ... # `$var' expands to a nonempty string
如果变量未设置或为空,则相反:
if [[ ! $var ]]; then ... # `$var' expands to the empty string (set or not)
要查看变量是否已设置(空或非空),我使用
if [[ ${var+x} ]]; then ... # `var' exists (empty or nonempty)
if [[ ${1+x} ]]; then ... # Parameter 1 exists (empty or nonempty)
如果变量未设置,则进行相反的测试:
if [[ ! ${var+x} ]]; then ... # `var' is not set at all
if [[ ! ${1+x} ]]; then ... # We were called with no arguments
其他回答
在Bash中,可以在[[]]内置函数中使用-v:
#! /bin/bash -u
if [[ ! -v SOMEVAR ]]; then
SOMEVAR='hello'
fi
echo $SOMEVAR
对于那些希望在使用set-u的脚本中检查未设置或空的脚本:
if [ -z "${var-}" ]; then
echo "Must provide var environment variable. Exiting...."
exit 1
fi
常规[-z“$var”]检查将因var而失败;未绑定变量如果设置-u但[-z“${var-}”]如果var未设置而不失败,则扩展为空字符串。
要测试是否设置了变量var:[${var+x}]。
若要测试变量是否按名称设置:[${!name+x}]。
要测试是否设置了位置参数:[${N+x}],其中N实际上是一个整数。
这个答案与莱昂内尔的答案几乎相似,但通过省略-z来探索一种更为简约的方法。
要测试是否设置了命名变量,请执行以下操作:
function is_set {
local v=$1
echo -n "${v}"
if [ ${!v+x} ]; then
echo " = '${!v}'"
else
echo " is unset"
fi
}
要测试是否设置了位置参数:
function a {
if [ ${1+x} ]; then
local arg=$1
echo "a '${arg}'"
else
echo "a: arg is unset"
fi
}
测试表明,不需要特别注意空格和有效的测试表达式。
set -eu
V1=a
V2=
V4=-gt
V5="1 -gt 2"
V6="! -z 1"
V7='$(exit 1)'
is_set V1
is_set V2
is_set V3
is_set V4
is_set V5
is_set V6
is_set V7
a 1
a
a "1 -gt 2"
a 1 -gt 2
$ ./test.sh
V1 = 'a'
V2 = ''
V3 is unset
V4 = '-gt'
V5 = '1 -gt 2'
V6 = '! -z 1'
V7 = '$(exit 1)'
a '1'
a: arg is unset
a '1 -gt 2'
a '1'
最后,请注意set-eu,它保护我们避免常见错误,例如变量名中的拼写错误。我建议使用它,但这意味着未设置的变量和带有空字符串的变量集之间的区别得到了正确处理。
如果你和我一样,你所寻找的其实是
“如果设置了变量,bash仅运行命令”
你希望这是一行,所以下面这行是你想要的
仅适用于Bash 4.2或更高版本
仅在设置时运行
if [[ -v mytest ]]; then echo "this runs only if variable is set"; fi
仅在未设置时运行
if [[ ! -v mytest2 ]]; then echo "this runs only if variable is not set"; fi
要检查非空/非零字符串变量,即如果已设置,请使用
if [ -n "$1" ]
它与-z相反。我发现自己使用-n多于-z。
您可以像这样使用它:
if [ -n "$1" ]; then
echo "You supplied the first parameter!"
else
echo "First parameter not supplied."
fi