我的if条件与gt比较值,如果值为null,但我想要比较null值,我只想要他只比较值
res=''
toto=5
if [[ "$toto" -gt "$res" ]]; then
...
else
...
fi
fi
解决方案是,但不是很好
if [[ ! -z "$res" ]]; then
if [[ "$toto" -gt "$res" ]]; then
...
else
...
fi
fi
使用&&
。
if [[ ! -z "$res" && "$toto" -gt "$res" ]]
您可以做出的其他改进:
! -z
替换-n
。((...))
进行数值比较。if [[ -n $res ]] && ((toto > res))
这个Shellcheck-clean代码以另一种方式处理空的$res
:
#! /bin/bash
res=''
toto=5
if [[ -z $res ]] ; then
: # $res is empty so don't compare with $toto
elif (( toto > res )); then
echo 'toto is greater than res'
else
echo 'toto is less than or equal to res'
fi
然而,它是否比问题中提出的“不太好”选项更好或更差是有争议的。更深的嵌套通常更糟糕,但最好避免使用其他链。我在这个答案中声称代码的唯一优势是,如果一个有用,它有一个方便的位置来发表有用的评论。