0

#!/bin/bash

echo -e "10\n20\n100\n200" > file.txt
number=0
cat file.txt | \
while read line
do
if test $line -gt 100
then
number=$line
echo "Inside while loop number=$number"
break
fi
done

echo "Outside while loop number=$number"

The output of this script is
Inside while loop number=200
Outside while loop number=0

Why the variable $number is losing its value outside while loop
even though it's a global value?

Thanks,
Mahendra

3
Contributors
2
Replies
4
Views
8 Years
Discussion Span
Last Post by fpmurphy
0

>Why the variable $number is losing its value outside while loop
even though it's a global value?

It has to do with the pipe

Read here and you might know why

0

You do not need to use the pipe. Instead use redirection

echo -e "10\n20\n100\n200" > file.txt

number=0
while read line
do
if test $line -gt 100
then
number=$line
echo "Inside while loop number=$number"
break
fi
done < file.txt

echo "Outside while loop number=$number"

You then get your expected output.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.