2017-02-20 138 views
2

我想在UNIX中構建一個非常基本的4函數算術腳本,它不喜歡我的算術語句。我試圖用「bash的算術」語法如何在UNIX中執行算術?

從這個來源

http://faculty.salina.k-state.edu/tim/unix_sg/bash/math.html

也當您引用在UNIX變量時,你需要使用「$」符號一個側面說明,你什麼時候不需要?

#!/bin/bash 

str1="add" 
str2="sub" 
str3="div" 
str4="mult" 

((int3=0)) 
((int2=0)) 
((int1=0)) 


clear 
read -p "please enter the first integer" $int1 
clear 
read -p "Please enter mathmatical operator'" input 
clear 
read -p "Please enter the second integer" $int2 


if [ "$input" = "$str1" ]; 
then 

((int3 = int1+int2)) 
    echo "$int3" 


else 

    echo "sadly, it does not work" 

fi; 
+1

可能重複[如何在bash腳本中添加數字](http://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in- a-bash-script) –

回答

0

使用bc命令

像這樣

echo "9/3+12" | bc

0

當你想要的變量值使用$read,不過,預計名稱的變量的

read -p "..." int1 

(從技術上講,你可以不喜歡

name=int1 
read -p "..." "$name" 

設置的int1值,因爲shell擴展name字符串int1,其中read然後用作名稱)。

+0

良好的反饋意見,我從我的變量中刪除了bash符號,但是我仍然在執行時遇到錯誤 – Anyon

+0

@JonathanDeal:哪個錯誤?你是什​​麼意思的「bash符號」。 '$'應該被認爲是一個給定變量值的一元運算符。 – cdarke

0

下面是一個快速的結束:

op=(add sub div mult) 

int1=0 
int2=0 
ans=0 

clear 
read -p "please enter the first integer > " int1 
clear 
IFS='/' 
read -p "Please enter mathmatical operator (${op[*]})> " input 
unset IFS 
clear 
read -p "Please enter the second integer > " int2 

case "$input" in 
    add) ((ans = int1 + int2));; 
    sub) ((ans = int1 - int2));; 
    div) ((ans = int1/int2));; # returns truncated value and might want to check int2 != 0 
    mult) ((ans = int1 * int2));; 
    *) echo "Invalid choice" 
      exit 1;; 
esac 

echo "Answer is: $ans" 

您還需要檢查用戶輸入的號碼:)

0

另外一個

declare -A oper 
oper=([add]='+' [sub]='-' [div]='/' [mul]='*') 

read -r -p 'Num1? > ' num1 
read -r -p "oper? (${!oper[*]}) > " op 
read -r -p 'Num2? > ' num2 

[[ -n "${oper[$op]}" ]] || { echo "Err: unknown operation $op" >&2 ; exit 1; } 
res=$(bc -l <<< "$num1 ${oper[$op]} $num2") 
echo "$num1 ${oper[$op]} $num2 = $res" 
1

我想這是你想要什麼:

#!/bin/bash 

str1="add" 
str2="sub" 
str3="div" 
str4="mult" 

((int3=0)) # maybe you can explain me in comments why you need a arithmetic expression here to perform an simple assignment? 
((int2=0)) 
((int1=0)) 

echo -n "please enter the first integer > " 
read int1 
echo -n "Please enter mathmatical operator > " 
read input 
echo -n "Please enter the second integer > " 
read int2 


if [ $input = $str1 ] 
then 
((int3=int1 + int2)) 
    echo "$int3" 
else 
    echo "sadly, it does not work" 
fi 

exec $SHELL 

你應該definitly結帳man bash。它在那裏記錄在哪個命令中,您需要指定$或不引用變量。但除此之外:

var=123 # variable assignment. no spaces in between 
echo $var # fetches/references the value of var. Or in other words $var gets substituted by it's value.