人。我是Linux和shell脚本的新手,我有一个问题。
我有以下简单的计算器:
input="yes"
while [[ $input = "yes" ]]
do
PS3="Press 1 for Addition, 2 for subtraction, 3 for multiplication and 4 for division: "
select math in Addition Subtraction Multiplication Division
do
case "$math" in
Addition)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 + $num2`
COUNTER=COUNTER+1
echo Answer: $result
break
;;
Subtraction)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 - $num2`
echo Answer: $result
break
;;
Multiplication)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 * $num2`
echo Answer: $result
break
;;
Division)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=$(expr "scale=2; $num1/$num2" | bc)
echo Answer = $result
break
;;
*)
echo Choose 1 to 4 only!!!!
break
;;
esac
done
done
我想要的只是能够计算操作(意味着成功操作是+1,比如" 2 + 5 = 7"并且一些计数器变量变为+1 ..然后是别的再次+1)直到用户输入一些东西来停止计算器。然后应该在新文件中写入计数器变量(保存执行的操作总数)。我怎么能这样做,或者有人能给我一个例子吗?
答案 0 :(得分:1)
您可以使用计数器:
count=0
((count++))
)后,使用$?
成功运行后递增计数器printf "%d\n" "$count" > file
不确定为什么每次都要写入新文件。如果这是所需的行为,则每次都可以生成新的文件名。也许,您可以将文件命名为operation.txt.N
,其中N是计数器。
您可以添加Quit
作为用户可以选择的选项:
PS3="Press 1 for Addition, 2 for subtraction, 3 for multiplication, 4 for division and 5 to Quit: "
select math in Addition Subtraction Multiplication Division Quit
... existing code here ...
并添加此案例:
Quit)
input=no
break
;;