2013-02-27 69 views
0

我想验证用户输入到一个小脚本我正在写检查,应该有:2个参数和第一个参数应该是枯萎“挂载”或“卸载”参数检查controll逻辑和语法混淆

我有以下几点:

if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then 

但是它似乎有点overzelouse在符合条件我想要的。例如用当前的||运算符,没有任何东西能通过验证器,但如果我使用运算符,一切都会如此。

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 

回答

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 
+0

工作得很好,非常感谢。 – Hyposaurus 2013-02-27 10:00:34