While read

Hello from Paris,

Here is a script that i wrote. I nammed this script sum.sh :

#! /bin/bash

sum=0
cat $1 | while read line
do
#set $line
sum=`expr $sum  +  1`
done
echo $sum 

When I execute this script with a 4 lines file as argument, it returns 0 and not 4 as i expected :

Somebody could explain to me why and how i can change this script to get 4 as return ?

Thank you !

such as it is (although there's a program for that, called wc :)):

sum=0
while read line; do
  sum=$((sum + 1))
done < $1
echo $sum
$ cat -n myFile
     1	this
     2	is
     3	a
     4	file
     5	here

$ ./myScript
5
1 Like

The reason is when you pipe the file to a while loop, it actually gets executed in a sub-shell:-

cat $1 | while read line

So the scope of the variable sum value is within the while loop. This is the reason why it prints 0 outside the while loop

You can resolve this by removing the pipe:-

sum=0
while read line
do
#set $line
sum=`expr $sum  +  1`
done < "$1"
echo $sum
2 Likes

Being a Korn shell user, myself, I often overlook the pipe / sub-shell thing in Bash.. it's good that you pointed that out to the OP :slight_smile:

Thank you both for your answers !