3

Am new to bash and whiptail so excuse the ignorance.

When assigning a var in the for loop, the new value of 20 is never set when using a Whiptail dialog. Any suggestions why ?

andy="10"
{
    for ((i = 0 ; i <= 100 ; i+=50)); do
        andy="20"
        echo $i
        sleep 1
    done
 } | whiptail --gauge "Please wait" 5 50 0 
# }
echo "My val $andy

2 Answers2

4

A command inside a pipeline (that is, a series of commands separated by |) is always executed in a subshell, which means that each command has its own variable environment. The same is true of the commands inside the compound command (…), but not the compound command {…}, which can normally be used for grouping without creating a subshell.

In bash or zsh, you can solve this problem using process substitution instead of a pipeline. For example:

andy="10"
for ((i=0 ; i <= 100 ; i+=50)); do
        andy="20"
        echo $i
        sleep 1
done > >(whiptail --gauge "Please wait" 6 50 0) 
echo "My val $andy

>(whiptail ...) will cause a subshell to be created to execute whiptail; the entire expression will be substituted by the name of this subshell's standard input (in linux, it will be something like /dev/fd/63, but it could be a FIFO on other OSs). > >(...) causes standard output to be redirected to the subshell's standard input; the first > is just a normal stdout redirect.

rici
  • 234,347
  • 28
  • 237
  • 341
  • Many thanks - substitution instead of a pipeline did the trick – user3761314 Jun 20 '14 at 20:04
  • @user3761314 I don't know if you've ever made your way back to StackOverflow... but if you come back, it would be nice to mark this answer as "accepted" (click the gray ✔ in the left margin of the answer near the votes). – Doktor J Sep 08 '22 at 22:06
  • @rici 8 years later, this answer helped me sort and solve days' worth of debugging I'd realized I was using `()` subshells in one area of my script, and happily rectified that... only to find out that piping to `dialog` for the gauge was munging my variables! – Doktor J Sep 08 '22 at 22:07
1

The statements inside {} are not ordinarily executed in a sub-shell. However, when you add a pipe (|) to it, they seem to be executed in a sub-shell.

If you remove the pipe to whiptail, you will see the update value of andy.

R Sahu
  • 204,454
  • 14
  • 159
  • 270