2017-02-20 134 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.