Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer expression expected

Tags:

bash

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:

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?)

thx

like image 285
LookIntoEast Avatar asked Aug 18 '11 16:08

LookIntoEast


1 Answers

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++.

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 string equality 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.

(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.)

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.

like image 63
Keith Thompson Avatar answered Oct 03 '22 19:10

Keith Thompson