3

I have a challenge with a variable value changed in a for loop and the value of that variable after the for loop and using tee

SCRIPT_1:

    STATUS=9
    for  SESSION in  A B C
    do
       STATUS=5
       echo "SESSION=$SESSION  STATUS=$STATUS"
    done 
    echo "STATUS=$STATUS"

output script_1 is:

    SESSION=A  STATUS=5
    SESSION=B  STATUS=5
    SESSION=C  STATUS=5
    STATUS=5

SRIPT_2:

    STATUS=9
    for  SESSION in  A B C
    do
       STATUS=5
       echo "SESSION=$SESSION  STATUS=$STATUS"
    done | tee /tmp/ses.txt
    echo "STATUS=$STATUS"

output_2 is:

    SESSION=A  STATUS=5
    SESSION=B  STATUS=5
    SESSION=C  STATUS=5
    STATUS=9

Why a different output when using tee after done command.

2

When you put a "| tee", the shell that is interpreting the script is forking a new shell for the loop. Inserting a sleep in the loop and launching the script in background gives this list of processes:

   PID TTY       TIME COMMAND
 21168 pts/0     0:00 sh
 21259 pts/0     0:00 ps
 11962 pts/0     0:00 sh
 21170 pts/0     0:00 sleep
 21171 pts/0     0:00 tee
 21169 pts/0     0:00 sh

As you can see, there is an additional shell at the end of the list. You can get the same result with this script:

STATUS=9
echo "" > /tmp/ses.txt
for  SESSION in  A B C
do
   STATUS=5
   echo "SESSION=$SESSION  STATUS=$STATUS" | tee -a /tmp/ses.txt
done
echo "STATUS=$STATUS"

but whitout the side effect you are mentioning.

  • 1
    More exactly, piping to anything (not just tee) runs in a subshell. I don't know what shell(s?) hp-ux uses, but bash ksh93 zsh have another option: for blah blah done > >(tee foo) works as a simple redirection not a pipe and thus sets the var(s) in the original shell. – dave_thompson_085 Nov 17 '16 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.