我正在尝试在UNIX中构建一个非常基本的4函数算术脚本,它不喜欢我的算术语句。我试图使用'bash arithmetic'语法
来自此来源
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;
答案 0 :(得分: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
您应该明确签出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.
答案 1 :(得分:0)
使用bc
命令
类似这样的事情
echo "9/3+12" | bc
答案 2 :(得分:0)
如果需要变量的值,请使用$
。但是,read
需要变量的名称:
read -p "..." int1
(从技术上讲,你可以做类似
的事情name=int1
read -p "..." "$name"
设置int1
的值,因为shell会将name
扩展为字符串int1
,然后read
将其用作名称。)
答案 3 :(得分: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"
您还需要检查用户是否输入数字:)
答案 4 :(得分: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"