0

I wrote following bash script. The read command creates variable var. if $var==5 then break loop.

    seq 10 | while read -r var
    do
      echo "read: $var"
      if [[ $var == 5 ]]; then
        echo "break loop: $var"
        break
      fi
    done
    
    echo "after loop: $var"

Here is the output

read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop: 

My question is: why after loop, $var is empty?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
PeopleMoutainPeopleSea
  • 1,492
  • 1
  • 15
  • 24
  • Also see [BashFAQ/024 (I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?)](https://mywiki.wooledge.org/BashFAQ/024). – pjh Feb 18 '23 at 01:41

1 Answers1

2

The variable isn't loop-local, and everything related to read and loops here are just red herrings. The behavior you're seeing is because the pipe starts a subshell. If you get rid of the pipe and run this code instead:

    while read -r var
    do
      echo "read: $var"
      if [[ $var == 5 ]]; then
        echo "break loop: $var"
        break
      fi
    done < <(seq 10)
    
    echo "after loop: $var"

Then it will print this instead:

read: 1
read: 2
read: 3
read: 4
read: 5
break loop: 5
after loop: 5