I am new to unix shell scripting,
in the below script "num" is an input file which contains a series of numbers example :
2
3
5
8
I want to add the above all numbers and want the result finally outside the while loop. it prints the value zero instead of the actual expected result. I have given export i within a loop but it did not work. any idea?
#!/bin/sh
#set -x
i=0
while read line
do
i=`expr $i + $line`
echo $i
export i
done< num
echo $i
BUT the below gives the expected output
#!/bin/sh
#set -x
i=0
until [ $i -eq 10 ]
do
i=`expr $i + 1`
done
echo "$i"
Here is a file "num" and its content
# more num
1
2
3
6
5
3
# more add.sh
#!/bin/sh #set -x
i=0
while read line
do i=`expr $i + $line`
done < num
echo "Final :$i"
# ./add.sh
Final :0
#
I changed the script as you said, but the output was zero. I need to get the total sum value outside the while loop.
What happens in last script is that if there is any blank line in "num" file then the expression i=`expr $i + $line` goes as i=`expr 10 + ` which is a syntax error.
so there are few solutions to but here are few.
delete all blank line or
2 . include a condition in script which will test either the line is blank or not.
#!/bin/sh #set -x
i=0
while read line
do
echo --------- $i
if [ "$line" ]; then
i=`expr $i + $line`
fi
done < num
echo - $i
What happens in last script is that if there is any blank line in "num" file then the expression i=`expr $i + $line` goes as i=`expr 10 + ` which is a syntax error.
so there are few solutions to but here are few.
delete all blank line or
2 . include a condition in script which will test either the line is blank or not.
#!/bin/sh #set -x
i=0
while read line
do
if [ "$line" ]; then
i=\`expr $i \+ $line\`
fi
done < num
echo - $i
Contents of the file is
1
2
3
4
5
6
~
~
~
~
~
~
~
On executing the script output for the num file is 21
Pradeep, There is no blank line in "num" file.my question is that why am not getting total sum value outside the while loop.? is it due to scope of the variable? but am getting value of the variable outside the 'until' loop. have a look at the script i posted in my first post. Thanks!
try changing the shell use ksh/bash and then try ..
$ cat num
1
2
3
$
$ cat a.sh
i=0 # Look i have not specified any shell here ..
while read j
do
if [ ! -z "$j" ] # CHECK IF LINE IS NOT ZERO ( EMPTY )
then
i=$(( $i + $j ))
fi
done < num
echo "Total is : [$i]"
$
$ bash a.sh ; ksh a.sh
Total is : [6]
Total is : [6]
$
I think most of the folks who answer questions here will focus on obtaining alternate solutions to problems, as opposed to digging to find why something does not work ... cheers, drl