#!/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

>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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.