D
D
Dima2016-05-29 00:27:25
linux
Dima, 2016-05-29 00:27:25

Why is the variable set inside the loop set to zero (bash script)?

Gentlemen, I'm writing a simple flow controller and I got into trouble, I feel that some kind of trifle, but I could not find it :(
The problem is that I process the loop and, if the condition is successful, I change the $freePipe variable to end the main loop, but I change it inside the second level loop and when I check it in the main loop to continue it or stop, then it is reset.Below is the simplified code

freePipe="0"
  while [ "$freePipe" == 0 ]
  echo $freePipe
  do
    echo "Начинаем подбор"
    echo $freePipe

    cat $ipListFile | while read line
    do
      freePipe=$line
      echo "1 - $freePipe"
    done
    echo "2 - $freePipe"
    sleep 1
  echo "3 - $freePipe"
  done

I need to display $freePipe and I always get freePipe=0 :(
Moreover, echo 1 shows the given value, and 2 and 3 show "0"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2016-05-29
@Di9

You call the outer cat command with the "|" pipeline, and everything that comes in a block after the pipeline will run in a separate shell. From here "echo 1 freePipe" will output the cat process internal variable, not your loop.
Yes, and to end the loop, use exit or break.
The break command can take an argument to end a loop of a particular nesting.
For example

while true
do
   while true
   do
      while true
      do
         break 2
         echo 3
      done
      echo 2
   done
   echo 1
done

will only output 1 because break will exit two nested loops, remaining in the third one (that is, the outermost one)

A
aol-nnov, 2016-05-29
@aol-nnov

while [ condition ]
do
  op1
  op2
done

and we still need to remember, it seems that in the code above there will be a subshell, an assignment inside it and then an exit. it is clear that this assignment will not be reflected in the parent shell.
By the way, the "simplified code" is kind of meaningless and merciless.

V
Vlad Zhivotnev, 2016-05-29
@inkvizitor68sl

A loaf and horns from a trolleybus.
gnu parallel or xargs will help you. https://debian.pro/1834

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question