2013-02-27 68 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