Skip to main content
1 of 4
Peter.O
  • 33.8k
  • 32
  • 120
  • 167

Why is my variable being localized in one 'while read' loop, but not in another seemingly similar loop.

Why do I get different values for $x from the snippets below?

#!/bin/bash x=1 echo fred>junk ; while read var ; do x=55 ; done <junk echo x=$x # x=55 .. I'd expect this result x=1 cat junk | while read var ; do x=55 ; done echo x=$x # x=1 .. but why? x=1 echo fred | while read var ; do x=55 ; done echo x=$x # x=1 .. but why? 
Peter.O
  • 33.8k
  • 32
  • 120
  • 167