Jay*_*Jay 370
在bash中,至少以下命令测试$ var是否为空:
if [[ -z "$var" ]]; then
# Do what you want
fi
Run Code Online (Sandbox Code Playgroud)
这个命令man test是你的朋友.
Chr*_*heD 103
推定bash:
var=""
if [ -n "$var" ]; then
echo "not empty"
else
echo "empty"
fi
Run Code Online (Sandbox Code Playgroud)
Dan*_*son 47
我也见过
if [ "x$variable" = "x" ]; then ...
Run Code Online (Sandbox Code Playgroud)
这显然非常强大且与shell无关.
此外,"空"和"未设置"之间存在差异.请参见如何判断bash shell脚本中是否未定义字符串?.
小智 30
if [ ${foo:+1} ]
then
echo "yes"
fi
Run Code Online (Sandbox Code Playgroud)
yes如果设置了变量,则打印.${foo:+1}设置变量时返回1,否则返回空字符串.
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}
Run Code Online (Sandbox Code Playgroud)
true如果未设置变量或将变量设置为空字符串(""),则会返回此值.
if [ -z "$MyVar" ]
then
echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
echo "The variable MyVar has something in it."
fi
Run Code Online (Sandbox Code Playgroud)
该问题询问如何检查变量是否为空字符串,并且已经给出了最佳答案.
但是我经过一段时间在PHP中进行编程后才登陆这里,我实际上搜索的是像在bash shell中工作的php中的空函数一样的检查.
在阅读完答案之后,我意识到我在bash中没有正确思考,但无论如何在那个时刻像php中的空函数在我的bash代码中会非常方便.
由于我认为这可能发生在其他人身上,我决定在bash中转换php空函数
根据php手册:
如果变量不存在或者其值是以下值之一,则该变量被视为空:
当然,无法在bash中转换null和false情况,因此省略它们.
function empty
{
local var="$1"
# Return true if:
# 1. var is a null string ("" as empty string)
# 2. a non set variable is passed
# 3. a declared variable or array but without a value is passed
# 4. an empty array is passed
if test -z "$var"
then
[[ $( echo "1" ) ]]
return
# Return true if var is zero (0 as an integer or "0" as a string)
elif [ "$var" == 0 2> /dev/null ]
then
[[ $( echo "1" ) ]]
return
# Return true if var is 0.0 (0 as a float)
elif [ "$var" == 0.0 2> /dev/null ]
then
[[ $( echo "1" ) ]]
return
fi
[[ $( echo "" ) ]]
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
if empty "${var}"
then
echo "empty"
else
echo "not empty"
fi
Run Code Online (Sandbox Code Playgroud)
演示:
以下代码段:
#!/bin/bash
vars=(
""
0
0.0
"0"
1
"string"
" "
)
for (( i=0; i<${#vars[@]}; i++ ))
do
var="${vars[$i]}"
if empty "${var}"
then
what="empty"
else
what="not empty"
fi
echo "VAR \"$var\" is $what"
done
exit
Run Code Online (Sandbox Code Playgroud)
输出:
VAR "" is empty
VAR "0" is empty
VAR "0.0" is empty
VAR "0" is empty
VAR "1" is not empty
VAR "string" is not empty
VAR " " is not empty
Run Code Online (Sandbox Code Playgroud)
在bash逻辑中说过,这个函数中的零检查可能会导致问题,任何使用此函数的人都应该评估这个风险,并且可能决定将这些检查切掉而只留下第一个.
| 归档时间: |
|
| 查看次数: |
381579 次 |
| 最近记录: |