linux - why is this variable not being changed? -
this question has answer here:
- assign value variable in loop 1 answer
i have larger script smaller 1 shows problem:
#!/bin/bash x=0 if [[ $x == 0 ]] ls | while read l x=5 echo "this file $l , set 5 --> $x" done fi echo "this should not 0 --> $x"
if variable set outside while loop works expect. bash version 3.2.25(1)-release (x86_64-redhat-linux-gnu). i'll feel dumb if obvious thing.
the x
being set 5 in sub-shell (because part of pipeline), , happens in sub-shell not affect parent shell.
you can avoid sub-shell , result expected using process substitution in bash
:
#!/bin/bash x=0 if [[ $x == 0 ]] while read l x=5 echo "this file $l , set 5 --> $x" done < <(ls) fi echo "this should not 0 --> $x"
now while
loop part of main shell process (only ls
in sub-process) variable x
affected.
we can discuss merits of parsing output of ls
time; largely incidental issue in question.
another option be:
#!/bin/bash x=0 if [[ $x == 0 ]] ls | { while read l x=5 echo "this file $l , set 5 --> $x" done echo "this should not 0 --> $x" } fi echo "this should 0 still, though --> $x"
Comments
Post a Comment