1

I know the output isn\t being recognized as integer but I fail to understand why? The file has more than 5 lines.

$ if [ "$(wc -l test.txt)" -gt "$5" ]; then
            echo changes found;
           else
            echo  No changes found;
           fi

bash: [: 6 test.xml: integer expression expected
No changes found
DevSolar
  • 63,860
  • 19
  • 125
  • 201
Oxycash
  • 95
  • 9
  • 3
    I guess that `$5`, the fifth command line argument, evaluates to an empty string, thereby confusing test – Ronald Jan 17 '22 at 14:17
  • 1
    ... or to another non-integer. – John Bollinger Jan 17 '22 at 14:18
  • 1
    Simply use `$(wc -l – F. Hauri Jan 17 '22 at 14:43
  • the error message references the left side of the comparison as the string `6 test.xml` (the output from the `wc` call; and assuming you meant to use `test.xml` instead of `test.txt` in the example code) and hence the rest of the error message `integer expression expected` (ie, `6 test.xml` is not an integer) – markp-fuso Jan 17 '22 at 14:57

1 Answers1

3

I just tried this:

wc -l test.txt

With following result:

5 test.txt

So the result contains a number, followed by the name of the file.

You can solve it like this:

wc -l test.txt | awk '{print $1}'

This only gives the number.

So, you might change your code into:

$ if [ "$(wc -l test.txt  | awk '{print $1}')" -gt "$5" ]; then

... and now correct:

$ if [ $(wc -l test.txt  | awk '{print $1}') -gt 5 ]; then
Dominique
  • 13,061
  • 14
  • 45
  • 83
  • 5
    `wc -l < test.txt` also works. `wc` doesn't print the file name if it's stdin. – John Kugelman Jan 17 '22 at 14:40
  • All this works great until it goes into if loop. $ if [ "$(wc -l test.txt | awk '{print $1}')" -gt "$5" ]; then echo Y; else echo X; fi bash: [: : integer expression expected X $ wc -l test.txt | awk '{print $1}' 6 – Oxycash Jan 17 '22 at 14:49
  • @Oxycash: I removed the double quotes and replaced `$5` (the fifth parameter) by `5` (the number five). Is it going better now? – Dominique Jan 17 '22 at 14:54
  • @Dominique that did it finally! – Oxycash Jan 17 '22 at 15:08