另一种方法是否定它们:
: ${PACKAGENAME:?'$PACKAGENAME variable is empty!'} #emits error and exits
[ -z "${PACKAGENAME#kakadu-v6_4-00902C}" ] || { #if var - str not empty do block
echo '$PACKAGENAME is not kakadu-v6_4-00902C'
exit 1
} >&2
上面的代码块首先测试if是否"$PACKAGENAME"
有任何值,如果没有,则错误退出并回显?'this'}
到stderr
。如果其父外壳仍然存在,则测试已通过,并且接下来测试是否从变量中删除“ kakadu ...”字符串会导致-z
字符串为空。如果不是,则它再次发出错误并退出外壳。如果您的外壳此时在执行该块之后仍然存在,则不存在。
最好在函数中实现这种事情。喜欢:
argeq() ( i= : ${2?^MERR: not enough parameters!} #$#>=2 || quit w/ err ^M == \r
z() { return $((${#1}>0)) ; } #return 1 if ${#1}>0 else 0
until z "${2+?}" $((i=i+1)) #until $2 is not set...
do ! z "$1" && z "${1#"$2"}" || #$1 != '' && $1 - $2 == '' or...
exit $((i${1:++1})) #exit $? == failed arg count
shift ; done #shift away one param ; continue loop
)
使用该功能,您可以提供系统允许的尽可能多的参数。如果您提供的少于2个,它将返回1并向发送一条消息stderr
。如果提供2个或更多参数,它将全部视为字符串,如果所有参数相同则返回0,而不是null,否则将返回参数编号,该编号首先会通过检查。
在您的情况下,可以像这样使用:
{
PACKAGENAME='kakadu-v6_4-00902C'
argeq "$PACKAGENAME" kakadu-v6_4-00902C &&
echo "kakadu-v6_4-00902C == $PACKAGENAME" ||
echo failure
! argeq "${PACKAGENAME#*-}" kakadu-v6_4-00902C &&
echo "kakadu-v6_4-00902C != ${PACKAGENAME#*-}" ||
echo failure
}
###OUTPUT###
kakadu-v6_4-00902C == kakadu-v6_4-00902C
kakadu-v6_4-00902C != v6_4-00902C
为了进一步说明,我将编写另一个函数:
aeqecho() { i=$((i+1)) #inc for line#
argeq "$@" && echo "$i : yay" || #allswell or
! e=$? ${2+:} return || #save $?; ! exclusive || to drop ERRs
echo "$i : shite - arg$e failed" #report failure
}
演示:
{ i= s=string
aeqecho $s #1
aeqecho $s $s #2
aeqecho "$s $s" #3
aeqecho "$s $s" "${s} string" #4
aeqecho "${s}1" $s string #5
aeqecho "" "" "" #6
aeqecho "" "$s" $s #7
aeqecho 1 "${s#$s}1" $((2-1)) #8
aeqecho $s $s $s $s $s $s $s $s $s $s $s $s stng #9
aeqecho $s $s $s $s $s $s $s $s $s $s $s $s string #10
}
输出:
ERR: not enough parameters!
2 : yay
ERR: not enough parameters!
4 : yay
5 : shite - arg2 failed
6 : shite - arg1 failed
7 : shite - arg1 failed
8 : yay
9 : shite - arg13 failed
10 : yay
-eq
对于整数是正确的,您要测试字符串或正则表达式(==
或=~
):mywiki.wooledge.org/BashGuide/TestsAndConditionals