bash 将变量与shell中的整数进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18133161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:01:48  来源:igfitidea点击:

Compare variable with integer in shell?

bashshell

提问by David Wright

I have an if statement I need to run, as long as the value I have stored in my $countervariable is greater than 5.

我有一个 if 语句需要运行,只要我存储在$counter变量中的值大于5.

Here is the respective section of my current (non-functioning) script:

这是我当前(非运行)脚本的相应部分:

if $counter > 5
then
    echo "something"
fi

The mistake I'm making is probably very obvious, but for some reason I couldn't find the solution online.. Thanks!

我犯的错误可能很明显,但由于某种原因我无法在网上找到解决方案..谢谢!

回答by konsolebox

Well that is quite simple:

嗯,这很简单:

if [ "$counter" -gt 5 ]
then
    echo "something"
fi

回答by Thomas

Arithmetic needs to be done between ((and )):

需要在((和之间进行算术运算))

if (( $counter > 5 ))

Incidentally, you can also leave off the $in arithmetic, though it doesn't hurt to keep it.

顺便说一句,您也可以不使用$in 算术,尽管保留它并没有什么坏处。