0

I have written a zsh script to find some files, loop through and process them. Once it's over, I need to know some state set by a flag inside the loop. But the modified value of the flag does not get reflected outside the while loop.

So I tried the loop without the find. This time, the modified value of flag persists outside the loop also.

Thanks for an explanation and a workaround for this.

'find | while' loop

flag=false
find . -name "*.sh" | while read line
do
    # check conditions, process the file 
    echo "flag = $flag"
    flag=true
    echo "flag = $flag"
done

echo "flag = $flag"

Output

flag = false
flag = true
flag = false

Simple while loop

i=1
flag=false
while [ $i -le 1 ] 
do
        echo "flag = $flag"
        (( i++ ))
        flag=true
        echo "flag = $flag"
done

echo "flag = $flag"

Output

flag = false
flag = true
flag = true
aalosious
  • 578
  • 6
  • 11
  • I'm not entirely sure, however, how `zsh` decides when to execute part of a pipeline in a subshell. `echo foo | read bar; echo $bar` displays `foo`. – chepner Aug 20 '15 at 20:01

1 Answers1

2

Try adding the shebang (#!) to the top of your script. It will run the script in it's own shell.

NOTE: I had eight .sh files in the directory I used it in.

#! /bin/zsh
flag=0
echo "Before: flag = $flag"
find . -name "*.sh" | while read line
do
  # check conditions, process the file 
  flag=$(($flag+1))
  echo "Inside: flag = $flag"
done
echo "After : flag = $flag"

output:

Before: flag = 0
Inside: flag = 1
Inside: flag = 2
Inside: flag = 3
Inside: flag = 4
Inside: flag = 5
Inside: flag = 6
Inside: flag = 7
Inside: flag = 8
After : flag = 8

Hope this helps.

MPH426
  • 49
  • 2