How to add two integer values in Linux?
#!/bin/bash
cd /pg
file=`ls -l |awk '{print $9}'`
list=()
for i in $file
do
echo $i
a=`cat /pg/$i | head -n 1 |awk '{print $8}'`
b=`cat /pg/$i | head -n 2 |awk '{print $8}'`
#a1=`echo "$a" | tr -d '"'`
#b1=`echo "$b" | tr -d '"'`
echo $a
echo $b
c="$(($a+$b))"
list=($c)
#a1=`cat /pg/$i | head -n 2 |awk '{print $8}'`
done
While executing the above code i'm getting the below error please help me to fix the issue output of the values is a=30
and b=30
but still not able to add both.
/bin/max_timetrack.sh: line 16: 30+30
30: syntax error in expression (error token is "30")
You're error is in this line:
b=`cat /pg/$i | head -n 2 |awk '{print $8}'`
head
won't give you the second line, but the n first lines.
So b
will actually be:
30
30
and not 30
how you said.
Hence the error,
30+30
30
You would need (while keeping your complicated structure):
b=`cat /pg/$i | head -n 2 |awk '{print $8}' | tail -n 1`
However!
There is a lot of useless/strange use of things in your little script:
This would be enough:
b=$(awk 'NR==2{print $8}' "/pg/$i")
Note the use of $(...)
instead of backticks, which is the same but to be preferred.
Same with this line
a=`cat /pg/$i | head -n 1 |awk '{print $8}'`
would better be
a=$(awk 'NR==1{print $8}' "/pg/$i")
Anyways, you can do the arithmetic inside awk
only:
c=$(awk 'NR<=2{sum+=$8}END{print sum}')
Also you're parsing ls
, which is a bad choice:
file=`ls -l | awk '{print $9}'`
Can't you just do this?
for i in *; do ... done
Depending on what you want to do with c
, you can probably write the whole script as one awk
command.