Skip to main content
Fixed title; improved formatting.
Source Link

Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

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

#!/bin/bash x=1 echo fred>junkfred > junk ; while read var ; do x=55 ; done <junk< 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? 

Why is my variable local 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? 

Why is my variable local 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? 
Post Reopened by Gilles 'SO- stop being evil' bash
edited tags; edited title
Link
Volker Siegel
  • 17.8k
  • 6
  • 56
  • 81

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

Post Closed as "Duplicate" by Gilles 'SO- stop being evil' bash
edited tags
Link
Gilles 'SO- stop being evil'
  • 866.5k
  • 205
  • 1.8k
  • 2.3k
Tweeted twitter.com/#!/StackUnix/status/50565346259779584
Source Link
Peter.O
  • 33.8k
  • 32
  • 120
  • 167
Loading