因此,我正在製作一個簡單的bash shell腳本計算器,並遇到了一個障礙。Linux shell腳本,檢查來自用戶的輸入
我似乎無法找出看到,如果用戶已經輸入+或 - 或/或*
我不知道我應該嘗試寫。我知道
echo "Enter + or - "
read input2
if [ $input2 = "+" ] then
echo "You entered $input2"
不起作用。那麼我應該爲基本操作員閱讀哪些內容?
編輯:擊殼正在使用
因此,我正在製作一個簡單的bash shell腳本計算器,並遇到了一個障礙。Linux shell腳本,檢查來自用戶的輸入
我似乎無法找出看到,如果用戶已經輸入+或 - 或/或*
我不知道我應該嘗試寫。我知道
echo "Enter + or - "
read input2
if [ $input2 = "+" ] then
echo "You entered $input2"
不起作用。那麼我應該爲基本操作員閱讀哪些內容?
編輯:擊殼正在使用
在bash,分號或then
之前需要換行符。
雙引號變量,以防止膨脹可能導致語法錯誤:
if [ "$input" = '+' ] ; then
您還可以切換到[[ ... ]]
條件語句不需要的參數報價:
if [[ $input = + ]] ; then
echo You entered +
fi
你有在右邊引用*
,否則它被解釋爲通配符模式,意思是「任何事物」。
嘗試if語句,如:
if [ $input = "+" ]
你有一些嚴重的語法問題。這裏有一個精緻的一個:
#!/bin/bash
echo "Enter + or - "
read input2
if [ "$input2" = "+" ]; then
echo "You entered $input2"
fi
輸出:
Enter + or -
+
You entered +
您可以打印一些與輸入時讀得。
read -p "Enter + or - " input2
一個簡單的方法是使用bash case語句,而不是如果這個計算器腳本的條件。
#!/bin/bash
echo "Enter + or - or * or /"
read input2
case $input2 in
'+')
echo "You entered $input2" ;;
'-')
echo "You entered $input2" ;;
'*')
echo "You entered $input2" ;;
'/')
echo "You entered $input2" ;;
*)
echo "Invalid input"
;;
esac
請注意案例'*'和最後一種情況*(不帶單引號)之間的區別。第一個將直接匹配'*'符號,但最後一個(沒有單引號)表示通配符。最後一個選項是用來捕獲所有無效輸入的通配符,這些輸入與我們正在尋找的任何情況都不匹配。
上面的腳本也可以修改得更短。
echo "Enter + or - or * or /"
read input2
case $input2 in
'+'|'-' |'*' |'/')
echo "You entered $input2" ;;
*)
echo "Invalid input"
;;
esac
這會尋找「+」或「 - 」或「*」或「/」在一個單一的情況下,並打印$輸入2否則將默認打印「無效輸入」。
您可以在此處詳細瞭解http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
case語句請務必註明您的變量。否則,'*'將被擴展爲文件名通配符。 – Barmar 2015-04-01 15:55:55
你用什麼外殼? – choroba 2015-04-01 15:56:36
請發佈實際腳本示例。很難說出你做錯了什麼。我甚至不確定你是否在你的問題中使用反引號作爲SO標記,或者因爲這是你在腳本中的實際情況。 – Barmar 2015-04-01 15:57:26