BASH没有bc :: if [echo`awk'BEGIN {print 0.001> 0.9}'-eq 0];然后做一些事情;科幻

时间:2013-11-22 19:42:31

标签: bash shell if-statement awk bc

请帮忙。怎么能完成这个

if [ echo `awk 'BEGIN{print 0.001>0.9}'` -eq 0 ]; then DO SOMETHING; fi

但这是错误的 我要做的是:如果第一个数字(0.001)如果大于0.9,那么DO SOMETHING。别的,没有 数字总是浮动,如0.001,0.03,0.89等...... 啊,我不能使用bc命令。

4 个答案:

答案 0 :(得分:5)

概括它:

function gt {
    awk -v n1=$1 -v n2=$2 'BEGIN {exit !(n1 > n2)}'
}

if gt 0.01 0.9; then
    do_something
fi

答案 1 :(得分:2)

这应该有效:

[[ $(awk 'BEGIN{print (0.001>0.9)}') -eq 0 ]] && DO SOMETHING

或者如果你想将变量传递给awk:

[[ $(awk -v a='0.001' -v b='0.9' 'BEGIN{print (a>b)}') -eq 0 ]] && echo "a is smaller"

答案 2 :(得分:1)

从字面上看,你现有的代码并没有变量,那么这就足够了:

DO SOMETHING

由于0.001永远不会大于0.9,awk应该打印0,当然等于0,所以整个测试没有任何变量就没有意义......

答案 3 :(得分:1)

$ cat ./tst.sh
function cmp {
    awk -v v1="$1" -v v2="$2" 'BEGIN{
        if      (v1 > v2) { diff =  1 }
        else if (v1 < v2) { diff = -1 }
        else              { diff =  0 }
        print diff
    }'
}

if [ $(cmp "$1" "$2") -eq  1 ]; then rslt="is greater than"; fi
if [ $(cmp "$1" "$2") -eq -1 ]; then rslt="is less than";    fi
if [ $(cmp "$1" "$2") -eq  0 ]; then rslt="is equal to";     fi

printf "%s %s %s\n" "$1" "$rslt" "$2"

$ ./tst.sh 0.001 0.9
0.001 is less than 0.9

$ ./tst.sh 0.9 0.001    
0.9 is greater than 0.001

$ ./tst.sh 0.9 0.9000
0.9 is equal to 0.9000