英文:
Mutilply calculation in Bash Script
问题
你的 Bash 脚本中出现问题是因为乘法运算符 *
在 Bash 中有特殊的含义,用于匹配文件名。为了正确执行乘法计算,你需要对 *
进行转义。你可以尝试以下修改:
#!/bin/bash
read -p "Enter your expression: " INPUT
operand1=$(echo $INPUT | cut -d' ' -f 1)
operator=$(echo $INPUT | cut -d' ' -f 2)
operand2=$(echo $INPUT | cut -d' ' -f 3)
case $operator in
"+") res=$((operand1 + operand2));;
"-") res=$((operand1 - operand2));;
"*") res=$((operand1 \* operand2));; # 乘法运算符 * 需要转义
"/") if [[ $operand2 -eq 0 ]]; then
echo "MATH ERROR"
continue
else
res=$(bc <<< "scale=2; $operand1 / $operand2")
fi;;
"%") res=$(bc <<< "$operand1 % $operand2");;
esac
echo "$res"
这个修正后的代码中,乘法运算符 *
已经被正确转义,应该可以正确执行乘法运算。如果你还有其他问题或需要进一步帮助,请随时告诉我。
英文:
I must write the code support 5 calculations (+, -, , /, %) in Bash Script. It get an input form: <num1> <operator> <num2> and return the result. But when i try multiply calculation (), it not return result
This is my code:
#!/bin/bash
read -p ">>" INPUT
operand1=$(echo $INPUT | cut -d' ' -f 1)
operator=$(echo $INPUT | cut -d' ' -f 2)
operand2=$(echo $INPUT | cut -d' ' -f 3)
case $operator in
"+") res=$((operand1 + $operand2));;
"-") res=$((operand1 - $operand2));;
"*") res=$((operand1 \* $operand2));;
"/") if [[ $operand2 -eq 0 ]]; then
echo "MATH ERROR"
continue
else
res=`echo "scale=2; $operand1 / $operand2" | bc`
fi;;
"%") res=`echo $operand1 % $operand2 | bc`;;
esac
echo "$res"
I also these way but it still not work
"*") res=$((operand1 * operand2));;
and
"*") res=`echo $operand1 \* $operand2 | bc`;;
What wrong here with my code in multiply calculation?? Please help me
答案1
得分: 1
我认为你遇到了Bash中的文件系统通配符,其中'*'是一个特殊字符,匹配当前目录中的文件。
可以通过添加以下内容来禁用它:
set -f
在你的代码块之前。有关set
的更多信息,请参阅 https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
还有其他各种策略在这里讨论:https://stackoverflow.com/questions/11456403/stop-shell-wildcard-character-expansion
有了这个设置,你就不需要在计算中使用反斜杠转义'*',而可以直接使用:
"*") res=$((operand1 * $operand2));;
英文:
I think you are encountering file system globbing in bash where '*' is magic and matches files in the current directory.
This can be disabled by adding:
set -f
To your script before your code block.
For more information on set see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
And there are various other strategies discussed here: https://stackoverflow.com/questions/11456403/stop-shell-wildcard-character-expansion
With this, you will not need to backslash '*' in your computation and go with:
"*") res=$((operand1 * $operand2));;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论