Bash 脚本和 bc
我正在尝试编写一个 bash 脚本,并且需要进行一些浮点数学运算。基本上我想做这样的事情:
NUM=$(echo "scale=25;$1/10" | bc)
if [ $? -ne 0 ]
then
echo bad
fi
我遇到的问题是 $?倾向于保存 echo 程序的输出,而不是 bc 调用的输出。有没有办法将 bc 程序的输出保存到变量中?
编辑:
感谢您的快速回复。这是看待问题的另一种方式。假设我稍微修改了脚本,使其看起来像这样:
#!/bin/bash
NUM=$(echo "scale=25;$1/10" | bc)
if [ $? -ne 0 ]
then
echo bad
exit
fi
echo "$NUM"
当用户输入正常的浮点值时,它工作正常:
bash script.sh 1.0
输出:
.1000000000000000000000000
但是,当用户输入不正确的值时,脚本无法恢复:
bash script.sh 1.0a
输出:
(standard_in) 1: parse error
什么我想做的就是让它优雅地退出。
I'm trying to write a bash script and I needed to do some floating point math. Basically I want to do something like this:
NUM=$(echo "scale=25;$1/10" | bc)
if [ $? -ne 0 ]
then
echo bad
fi
The problem I'm running into is $? tends to hold the output from the echo program and not the bc call. Is there a way I save the output from the bc program into a variable?
EDIT:
Thanks for the quick replies. Here's another way of looking at the problem. Say I modified the script a little bit so it looks like this:
#!/bin/bash
NUM=$(echo "scale=25;$1/10" | bc)
if [ $? -ne 0 ]
then
echo bad
exit
fi
echo "$NUM"
When the user inputs a normal floating point value, it works fine:
bash script.sh 1.0
output:
.1000000000000000000000000
However, when the user enters an incorrect value, the script can't recover:
bash script.sh 1.0a
output:
(standard_in) 1: parse error
What I'm trying to do is get it to exit gracefully.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没看出有什么问题。 $NUM 应该保存您的 bc 命令结果,
请参阅:
输出
另一种方法是使用 awk
另一种方法是在传递给 bc 之前检查“$1” >。例如,
您不必再从
bc
检查$?
I don't see anything wrong. $NUM is supposed to hold your
bc
command resultssee:
output
another way is to use awk
The other way, is to do the check of "$1" before you pass to
bc
. egyou don't have to check for
$?
frombc
anymore对于 GNU bc,将在 stderr 上输出类似于“(standard_in) 1: 语法错误”的错误。您可以在变量中捕获它并检查它。
For GNU
bc
, an error similar to "(standard_in) 1: syntax error" will be output on stderr. You can capture this in your variable and check for it.您是在寻找 bc 的计算结果(存储在 NUM 中)还是系统调用的状态返回?
正如我所说,您在
$NUM
中得到了计算结果:测试:
Are you after the result of calculation from bc (which you store in NUM) or the status return from the system call?
As I said you have the result of calculation in
$NUM
:Test: