【发布时间】:2016-06-28 19:59:42
【问题描述】:
所以我必须用一些简单的函数在 bash 中制作这个小计算器,您可以在下面的代码中看到这些函数(这是调试版本)。但是,在执行过程中,我遇到了一个问题,将 * 输入到 operation2 中会给我 [: too many arguments,但这不会发生在 operation1 中。
我需要计算器将此输入用于 1+1*2 等输入,因为脚本需要继续运行,直到用户输入“=”,因此 while !环形。我是批处理脚本的新手,所以我不知道我必须改变什么。我从调试中知道它正在调用该脚本所在的字典中的文件列表,所以我相信它一定是误解了命令。
代码如下,在任一操作中读取 * 时发生的问题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
【问题讨论】:
-
你试过直接用
'*'代替*吗? -
*unquoted 是一个 shell 通配符。 -
那行得通,谢谢,但是这背后的要点是它被任何老用户使用,所以我真的需要它,这样就可以输入 *。
-
这个问题怎么不影响第一个操作输入呢?
-
+ read number3 4 ++ echo '2'\''*'\''4' ++ bc (standard_in) 1: 非法字符: ' (standard_in) 1: 非法字符: '
标签: linux bash loops while-loop calc