0

I am having a difficulty with an arithmetic syntax error.

I am reading the name of text files from the command line and count the number of the lines of each file.

NUM=$(wc -l "$text") 

and then I want to check whether NUM is odd or not.

So I put,

REMAINDER=$(( $NUM % 2 ))
if [ $REMAINDER -ne 0 ] ; then 
    echo "Odd number"
fi

However, it seems like there is a problem with

REMAINDER=$(( $NUM % 2 ))

$NUM doesn't seem to be regarded as a number but a '.txt' file. When I checked NUM by itself and it worked fine...

4

If you print $NUM, after

NUM=$(wc -l "$text") 

you probably will see (on Linux) a number and a filename on the same line, with some whitespace.

For example:

1842 basic.c

That string isn't a number, and you usually would read just the first token with your choice of shell/sed/awk, etc., to use that as a number.

@steeldriver suggests this for getting just the number:

NUM=$(wc -l < "$text")

which works (tested with Debian).

  • 1
    ... or use wc -l < "$text" (wc should return only the count when reading input via stdin instead of from a named file) – steeldriver Feb 24 '16 at 1:28
  • There are several variations (and aside from Linux, several systems that could be considered). – Thomas Dickey Feb 24 '16 at 1:29
  • Thank you so much for your reply! Yes it prints both the number and the name of the file when I do that. I'll try to take the number only as you suggest! I'll be able to choose your answer in 5 minutes! – pigletwithcurls Feb 24 '16 at 1:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.