期望Bash整数表达式 [英] Bash integer expression expected

查看:72
本文介绍了期望Bash整数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要满足功能要求,我必须检索一个占空系数(0.01%中为0-100%).

To satisfy function requirements I have to retrieve a parameter which is a duty cycle (0-100% in 0.01%).

为了测试,我写了一些简单的东西:

For test, I wrote something simple like :

#!/bin/bash
#

if [ "$1" -lt 0 ] || [ "$1" -gt 100 ]
then
    echo "bad param"
else
    echo "ok"
fi  

我获得了:

root@:~# ./test.sh 11
ok
root@:~# ./test.sh 11,01
./test.sh: line 4: [: 11,01: integer expression expected
./test.sh: line 4: [: 11,01: integer expression expected
bad param

如何实现这种测试?

推荐答案

bash 只能以整数算术运算.如果需要浮动,请使用 bc :

bash can only operate in integer arithmetics. If you need floats, use an external tool like bc:

if (( $( bc <<< "($1 < 0) || ($1 > 100) " ) )) ; then
    ...
fi

尽管整个语言(例如Perl)/

I would rather switch to a more powerful language for the whole script, though (like Perl)/

这篇关于期望Bash整数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆