我想檢查用戶是否在命令行中使用case和if/else語句鍵入多個參數。有什麼不對的是,我一直得到默認情況下,而不是相同的命令,但有2多個參數。例如,我的條件之一是:Bash:否則在case語句中的if/else語句不工作
del)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: removes a file"
else
echo "using Bash command: rm $2 $3"
rm $2 $3
echo done
fi
打印的首要條件,但如果我輸入,也就是說,德爾AAA BBB,我得到默認情況下,它是:
echo "ERROR: Unrecognized command"
我如果有幫助,也可以使用它讀取用戶的輸入。
read -p "wcl> " -r wcl $2 $3
我真的不知道是否有解決這個不殺我所有的代碼,並從頭開始一個更好的辦法。 這是全碼:
#!/bin/bash
#use read command
echo Welcome to the Windows Command Line simulator!
echo Enter your commands below
while true
do
read -p "wcl> " -r wcl $2 $3
case $wcl in
dir)
echo "using Bash command: ls $2 $3"
ls
continue
;;
copy)
FILE="$2"
if [ "$#" -ne 3 ]
then
echo "Usage: copy sourcefile destinationfile"
else
echo "using Bash command: cp $2 $3"
if [ -f "$FILE" ]
then
cp $2 $3
else
echo "cannot stat $FILE: No such file or directory">&2
fi
echo done
fi
continue
;;
del)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: removes a file"
else
echo "using Bash command: rm $2 $3"
rm $2 $3
echo done
fi
continue
;;
move)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: moves a file to another file name and location"
else
echo "using Bash command: mv $2 $3"
mv $2 $3
echo done
fi
continue
;;
rename)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: renames a file"
else
echo "using Bash command: mv $2 $3"
mv $2 $3
echo done
fi
continue
;;
ipconfig)
ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1
continue
;;
exit)
echo "Goodbye"
exit 1
;;
^c)
echo "Goodbye"
exit 1
;;
*)
echo "ERROR: Unrecognized command"
continue
esac
done
檢查命令行參數個數的最好方法是測試'$#',例如'if(($#<2))'。 – cdarke
你需要顯示你的代碼的其餘部分,特別是'case .. in'部分。 – SiKing