我正在尝试验证用户输入我正在编写的小脚本,检查应该有:2个参数,第一个参数应该是'mount'或'unmount'
我有以下内容:
if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then
然而,在满足我想要的条件时似乎有点过分。例如,使用当前的||操作员,没有任何东西通过验证器,但如果我使用&&操作员一切都好。
if [ ! $# == 2 ] && [ $1 != "mount" -o $1 != "unmount" ]; then
有人可以帮我解决这个问题吗?
这是整个块和预期用途
if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then
echo "Usage:"
echo "encmount.sh mount remotepoint # mount the remote file system"
echo "encmount.sh unmount remotepoint # unmount the remote file system"
exit
fi
答案 0 :(得分:1)
你可以这样做:
if [ "$#" -ne 2 ] || [ "$1" != "mount" -a "$1" != "unmount" ]; then
echo "Usage:"
echo "encmount.sh mount remotepoint # mount the remote file system"
echo "encmount.sh unmount remotepoint # unmount the remote file system"
exit -1
fi
echo "OK"
您的测试中存在一个小的逻辑错误,因为如果$1
不等于"mount"
和"unmount"
,则应输入使用分支。您还应该将数字与-eq
和-ne
运算符(see here)进行比较,或使用((
))
。
请注意,您应该在test
([
]
)
您还可以将这两个表达式组合在一起:
if [ "$#" -ne 2 -o \( "$1" != "mount" -a "$1" != "unmount" \) ]; then
如果你有bash,你也可以使用[[
]]
语法:
if [[ $# -ne 2 || ( $1 != "mount" && $1 != "unmount" ) ]]; then