bash脚本编程和bc [英] Bash Scripting and bc
问题描述
我试图写一个bash脚本,我需要做一些浮点运算。基本上我想要做这样的事情:
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
我遇到的问题是$?倾向于保持从回波程序的输出,而不是公元前呼叫。有没有一种方法,我从BC程序的输出保存到一个变量?
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?
编辑:
感谢您的快速回复。下面是看问题的另一种方式。说我修改剧本一点点,所以它看起来是这样的:
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
输出:
.1000000000000000000000000
然而,当用户输入一个不正确的值,则脚本不能恢复
However, when the user enters an incorrect value, the script can't recover:
bash script.sh 1.0a
输出:
(standard_in) 1: parse error
我想要做的就是它优雅地退出。
What I'm trying to do is get it to exit gracefully.
推荐答案
我看不出有什么毛病。 $ NUM应该握住你的 BC
命令结果
I don't see anything wrong. $NUM is supposed to hold your bc
command results
请参阅:
NUM=$(echo "scale=25;$1/10" | bc)
echo "\$? is $?"
echo "NUM is $NUM"
输出
$ ./shell.sh 10
$? is 0
NUM is 1.0000000000000000000000000
另一种方法是用awk
another way is to use awk
NUM=$(awk -vinput="$1" 'BEGIN{printf "%.25f", input/10 }')
echo "\$? is $?"
echo "NUM is $NUM"
另一种方法,就是做的$ 1传递给 BC
前的检查。例如:
shopt -s extglob
input="$1"
case "$input" in
+([0-9.]))
IFS="."; set -- $input
if [ $# -ne 2 ];then
echo "bad decimal"
else
NUM=$(echo "scale=25;$1/10" | bc )
echo "$NUM"
fi
esac
您不必从检查
了 $?
BC
you don't have to check for $?
from bc
anymore
这篇关于bash脚本编程和bc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!