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
  • 67,862
  • 21
  • 134
  • 209
Oxycash
  • 167
  • 12

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
  • 16,450
  • 15
  • 56
  • 112
  • 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