Skip to main content
Added references and an additional solution.
Source Link
igal
  • 10.2k
  • 4
  • 45
  • 60

In this caseyour example the while-loop is executed in a subshell, so changes to the variable inside the while-loop won't affect the external variable. TryThis is because you're using the followingloop with a pipe, which automatically causes it to run in a subshell.

Here is an alternative solution using a while loop:

i=1
while read x; do
   i=$(($i + 1))
   echo $i
done <<<$(find tmp -type f)
echo $i

And here is the same approach using a for-loop instead:

i=1
for x in $(find tmp -type f);
do 
   i=$(($i + 1))
   echo $i
done
echo $i

For more information see the following posts:

Also look at the following chapter from the Advanced Bash Scripting Guide:

In this case the while-loop is executed in a subshell, so changes to the variable inside the while-loop won't affect the external variable. Try the following for-loop instead:

i=1
for x in $(find tmp -type f);
do 
   i=$(($i + 1))
   echo $i
done
echo $i

In your example the while-loop is executed in a subshell, so changes to the variable inside the while-loop won't affect the external variable. This is because you're using the loop with a pipe, which automatically causes it to run in a subshell.

Here is an alternative solution using a while loop:

i=1
while read x; do
   i=$(($i + 1))
   echo $i
done <<<$(find tmp -type f)
echo $i

And here is the same approach using a for-loop:

i=1
for x in $(find tmp -type f);
do 
   i=$(($i + 1))
   echo $i
done
echo $i

For more information see the following posts:

Also look at the following chapter from the Advanced Bash Scripting Guide:

Source Link
igal
  • 10.2k
  • 4
  • 45
  • 60

In this case the while-loop is executed in a subshell, so changes to the variable inside the while-loop won't affect the external variable. Try the following for-loop instead:

i=1
for x in $(find tmp -type f);
do 
   i=$(($i + 1))
   echo $i
done
echo $i