Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to accumulate the line size of a number of files contained in a folder. I have written the following script:

let a=0
let num=0
for i in folder/*
do
        num=`cat $i | wc -l`
        a=$a+$num
done
echo $a

What i am geting at the end of the script is 123+234+432+... and not the result of the arithmetic operation of addition.

share|improve this question

2 Answers 2

up vote 11 down vote accepted

Your arithmetic evaluation syntax is wrong. Use any of the following (the first is extremely portable but slow, the second is POSIX and portable except to the Bourne shell and earlier versions of the Almquist shell, the last three require ksh, bash or zsh):

a=`expr "$a" + "$num"`

a=$(($a+$num))

((a=a+num))

let a=a+num

((a+=num))

Or you can just skip the entire for loop and just do:

wc -l folder/*

Or, if you only want the total:

cat folder/* | wc -l

Or with zsh and its mult_ios option:

wc -l < folder/*
share|improve this answer
    
Thanks for the addition, @StephaneChazelas. –  manatwork Nov 7 '12 at 14:33

you can also use this code

    a=`expr $a + $num`
    echo $a

and MAKE SURE THAT THER IS A SPACE ON BOTH SIDE OF + IN $a + $num

share|improve this answer
    
always give space on both sides of operator when using expr command for calculation. –  user1678213 Nov 7 '12 at 10:45

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.