bash 预期的整数表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7110723/
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
Integer expression expected
提问by LookIntoEast
I want to read my files line by line every 5 seconds. This time I just tried one-line bash command to do this. And bash command is:
我想每 5 秒一行一行地读取我的文件。这次我只是尝试了单行 bash 命令来执行此操作。bash 命令是:
let X=1;while [ $X -lt 20 ];do cat XXX.file |head -$X|tail -1;X=$X+1;sleep 5;done
However I got the error like:
但是我得到了这样的错误:
-bash: [: 1+1: integer expression expected
What's the problem? btw, why can't we do $X < 20? (Instead we have to do -lt, less than?)
有什么问题?顺便说一句,为什么我们不能做 $X < 20?(相反,我们必须做 -lt,小于?)
thx
谢谢
回答by Keith Thompson
Your assignment X=$X+1
doesn't perform arithmetic. If $X
is 1, it sets it to the string "1+1"
. Change X=$X+1
to let X=X+1
or let X++
.
您的作业X=$X+1
不执行算术运算。如果$X
是 1,则将其设置为 string "1+1"
。更改X=$X+1
为let X=X+1
或let X++
。
As for the use of -lt
rather than <
, that's just part of the syntax of [
(i.e., the test
command). It uses =
and !=
for stringequality and inequality -eq
, -ne
, -lt
, -le
, -gt
, and -ge
for numbers. As @Malvolio points out, the use of <
would be inconvenient, since it's the input redirection operator.
至于使用-lt
而不是<
,那只是[
(即test
命令)语法的一部分。它使用=
和!=
表示字符串相等和不相等-eq
, -ne
, -lt
, -le
, -gt
, 和-ge
表示数字。正如@Malvolio 指出的那样,使用<
会很不方便,因为它是输入重定向运算符。
(The test
/ [
command that's built into the bash shell does accept <
and >
, but not <=
or >=
, for strings. But the <
or >
character has to be quoted to avoid interpretation as an I/O redirection operator.)
(bash shell 中内置的test
/[
命令确实接受<
and >
,但不接受<=
or >=
,用于字符串。但必须引用<
or>
字符以避免解释为 I/O 重定向运算符。)
Or consider using the equivalent (( expr ))
construct rather than the let
command. For example, let X++
can be written as ((X++))
. At least bash, ksh, and zsh support this, though sh likely doesn't. I haven't checked the respective documentation, but I presume the shells' developers would want to make them compatible.
或者考虑使用等效的(( expr ))
构造而不是let
命令。例如,let X++
可以写成((X++))
. 至少 bash、ksh 和 zsh 支持这一点,尽管 sh 可能不支持。我没有检查相应的文档,但我认为 shell 的开发人员希望使它们兼容。
回答by Malvolio
Iwould use
我会用
X=`expr $X + 1`
but that's just me. And you cannot say $X < 20 because < is the input-redirect operator.
但这只是我。你不能说 $X < 20 因为 < 是输入重定向操作符。
回答by Luke Morgan
The sum X=$X+1
should be X=$(expr $X + 1 )
.
总和X=$X+1
应该是X=$(expr $X + 1 )
。
You can also use <
for the comparison, but you have to write (("$X" < "20"))
with the double parenthesis instead of [ $X -lt 20 ]
.
您也可以<
用于比较,但您必须(("$X" < "20"))
使用双括号而不是[ $X -lt 20 ]
.