42

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.

0

6 Answers 6

77

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/*
3
  • 2
    No need for the $ inside ((...)). a=$((a+num)) is already fine. Commented Feb 7, 2018 at 8:08
  • if a variable is not set or having null value, would this work, if no any other way to handle that.
    – Bharat
    Commented Sep 14, 2018 at 13:10
  • $((a+num)) is slightly faster than $(($a+$num)), tested in bash.
    – lxvs
    Commented Jul 11, 2022 at 7:10
8

you can also use this code

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

and MAKE SURE THAT THERE IS A SPACE ON BOTH SIDES OF + IN "$a + $num"

1
  • always give space on both sides of operator when using expr command for calculation. Commented Nov 7, 2012 at 10:45
4

The answer needs to specify in which shell the code is valid. For instance in the bourne Shell (sh) only the following instructions are valid:

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

while the other possibilities listed by @manatwork may be valid in bourne again shell (bash)

2

You could declare the type of variable first:

    declare -i a=0
    declare -i num=0
1

Sorry, previous edit was for a different post. Here, just a small modification to the original script:

let a=0
let num=0
for i in folder/*
do
        num=`cat $i | wc -l`
        a=$(echo $a+$num|bc)
done
echo $a
2
  • 1
    Voted down, as the answer doesn't appear to address the question.
    – Time4Tea
    Commented Jan 30, 2018 at 22:07
  • Sorry guys, now corrected
    – Leo
    Commented Jan 30, 2018 at 22:22
-1

i make it like this

MY_VARIABLE=$((num1+num2))
2
  • 4
    This adds nothing to what has already been said.
    – Kusalananda
    Commented Aug 5, 2018 at 14:33
  • 1
    it is the brief answer Commented Aug 5, 2018 at 16:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .