need to read lines in file and compare value in if not working

Hello,

I have this file that sometime contains 0 lines and sometimes 1 or more.

It's supposed to then put the result (could be 0 or 1 or 2 or more) into a variable.

Then it's supposed to echo using an if else statement depending on the value of the variable.

flagvar='wc -l $tempfile | awk '{print $1}''

if [ $flagvar != "0" ]; then
   echo $flagvar
else
   echo "the file does not have rows"
fi

The problem is that the tempfile contains 2 rows and it always echoes that
"the file does no have rows."

I've tried $flagvar != "0", I'm wondering if the condition should be a string since the result is printed from awk. (if the "0" is correct).. it I just used the value 0 without the quotes this would just be like $flagvar!=true which is not equal to true.

You don't need to use awk to get a result from wc -l, that's severe overkill.

LINES=$(wc -l < inputfile)

You're also comparing as strings, not integers. Try mathematical comparison:

if [ "$LINES" -gt 0 ]
then
        echo "Has $LINES lines"
else
        echo "has no lines"
fi
1 Like