2017-02-11 102 views
0

我想寫一個計算器腳本,但第一個if阻止elif。我的意思是,當我嘗試運行它時,我按1,但它運行,就好像我按了2.這是我的代碼。您的病情元素之間Bash如果阻止elif

echo "For Advanced mode press 1" 
echo "For Help press 2" 

loop=1 
while [ $loop=1 ]; do 

    read n 

    if [ $n=2 ]; then 
      echo "To use the calculator follow the promptings." 
      echo "If asked, the operators are: " 
      echo "* for multiplication,/for division." 
      echo "+ for addition, - for subtraction." 
      echo "% for modulus, which is division remainder" 
      echo "== is equal to, != is not equal to." 
      echo "** for exponents" 
      n="" 

    elif [ $n=1 ]; then 
      read a 
      break 
    fi 

done 
echo "_______________________" 
echo "What would you like to do?" 
echo "Press 1 for basic arith" 
echo -n "Press 2 for geometry" 
read choice 
loop=2 

if [ $choice=1]; then 
    while [ $loop=2 ]; do 
     echo -n "Enter X Value: " 
     read x 
    echo -n "Enter Operator: " 
    read op 
    echo -n "Enter Y Value: " 
    read y 
    ans=$((x $op y)) 
    echo "$x $op $y = $ans" 
    echo "____________________" 
    echo "To input a new function, press enter" 
    read cont 
    done 
fi 

回答

0

看跌空間,如$n = 2$n=2。你應該通過它的參數作爲空格隔開的話。所以你的代碼應該如下:

echo "For Advanced mode press 1" 
echo "For Help press 2" 

loop=1 
while [ $loop = 1 ]; do 

    read n 

    if [ $n = 2 ]; then 
     echo "To use the calculator follow the promptings." 
     echo "If asked, the operators are: " 
     echo "* for multiplication,/for division." 
     echo "+ for addition, - for subtraction." 
     echo "% for modulus, which is division remainder" 
     echo "== is equal to, != is not equal to." 
     echo "** for exponents" 
     n="" 

    elif [ $n = 1 ]; then 
     read a 
     break 
    fi 

done 
echo "_______________________" 
echo "What would you like to do?" 
echo "Press 1 for basic arith" 
echo -n "Press 2 for geometry" 
read choice 
loop=2 

if [ $choice = 1 ]; then 
    while [ $loop = 2 ]; do 
     echo -n "Enter X Value: " 
     read x 
    echo -n "Enter Operator: " 
    read op 
    echo -n "Enter Y Value: " 
    read y 
    ans=$((x $op y)) 
    echo "$x $op $y = $ans" 
    echo "____________________" 
    echo "To input a new function, press enter" 
    read cont 
    done 
fi 
3

[ built-in用於評估條件。在開幕之後必須有一個空格[以及在結束之前的空格],否則它的語法不正確。

[ ... ]表達式中,可以使用各種條件運算符。一個這樣的運營商是=。您必須在操作員前後放置空格,否則不會將其識別爲操作員。

例如,[ $n=2 ]其中n的值爲1,將被評估爲[ 1=2 ]1=2未被評估爲條件,因爲它周圍沒有空格。 1=2將被評估爲字符串「1 = 2」。並且Bash中的任何非空字符串都是truthy,因此聲明[ 1=2 ]會生成真實的,即使它不「看起來」,也是如此。

您必須編寫[ "$n" = 2 ],以便=被解釋爲條件運算符,並且該表達式不會變成單個字符串。請注意,空格在Bash中非常重要。空格將程序的邏輯元素分開,而不將空格表達式連接爲字符串。

另請注意,我在變量周圍添加了雙引號。這是爲了在變量爲空時保護表達式。例如,如果您編寫了[ $n = 2 ]且變量爲空,則該表達式將被評估爲[ = 2 ],這是一個格式錯誤的表達式,並且該腳本將因錯誤而崩潰。

+0

不錯的答案。 '['計算它給出的參數的數量,並根據該數量做不同的事情。還要注意,bash的內建'[['對於未加引號的變量更爲明智(它們被空字符串替代,所以它們不會「失去它們的位置」作爲參數)。 –