Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 4 down vote accepted

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

share|improve this answer
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 at 1:28
    
There are several variations (and aside from Linux, several systems that could be considered). – Thomas Dickey Feb 24 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 at 1:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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