所以我必须使用一些简单的函数在bash中创建这个小计算器,您可以在下面的代码中看到它(这是调试版本)。但是在执行期间我遇到一个问题,输入* into operation2给了我[:太多的参数,但是这不会发生在operation1中。
我需要计算器将此输入用于输入,例如1 + 1 * 2等,因为脚本需要继续运行,直到用户输入“=”因此一会儿!环。我是批处理脚本的新手,所以我不知道我要改变什么。我知道从调试它调用了这个脚本所在的字典中的文件列表,所以我认为它必须误解命令。
代码如下,当在任一操作2上读取*时发生问题。但它适用于所有其他输入(+, - ,/,=)
#bin/bash +x
begin=$(date +"%s")
echo "Please Enter Your Unix Username:"
read text
userdata=$(grep $text /etc/passwd | cut -d ":" -f1,5,6 | tr -d ',')
echo "The User: $userdata" >> calcusers.txt
date=$(date)
echo "Last Ran calculator.sh on: $date " >> calcusers.txt
echo "---------------------------------------------------------" >> calcusers.txt
name=$(grep $text /etc/passwd | cut -d ":" -f5 | cut -d\ -f1)
echo -n "Hello" $name && echo ", Welcome to calculator.sh."
echo "To begin using calculator.sh to do some calculations simply type a number"
echo "below, followed by the type of sum you want to perform and the input for"
echo "a second number, third and so on. To output the equation simply type =."
set -x
echo "Please Enter a Number:"
read number1
echo "Would you like to Add(+), Subtract(-), Multiply(*) or Divide(/) that number?"
read operation1
echo "Please Enter a Number:"
read number2
total=$(echo "$number1$operation1$number2" | bc)
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
while [ ! $operation2 = "=" ]
do
echo "Please Enter a Number:"
read number3
total=$(echo "$total$operation2$number3" | bc)
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
done
set +x
echo -n "The total of the equation is" $total && echo "."
termin=$(date +"%s")
difftimelps=$(($termin-$begin))
echo "Thanks for using calculator.sh!"
echo "$(($difftimelps / 60)) minutes and $(($difftimelps % 60)) seconds has passed since the Script was Executed."
exit 0
答案 0 :(得分:2)
在任何地方引用你的变量:
while [ ! "$operation2" = "=" ]
# ........^............^
此外,您应该期望来自用户的无效输入
while [ ! "$operation2" = "=" ]
do
case "$operation2" in
[*/+-])
echo "Please Enter a Number:"
read number3
total=$(echo "$total$operation2$number3" | bc)
;;
*) echo "Invalid operation: '$operation2'"
;;
esac
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
done