Bibindoum
Bibindoum

Reputation: 21

When piping a command to shell script, why does exiting piped command makes shell script exit?

First of all, sorry if the title is not clear or misleading, my question is not not exactly easy to be understood out of context.

So here it is: I am running a shell script (hello.sh) that needs to relocate itself from /root to /. thus I made a simple recursion, to test from where the script is running and to make a temporary copy and launch it and exit(this last temporary copy will move the original file, and delete itself while still running).

#!/bin/sh    

IsTMP=$(echo $0 | grep "tmp")
if [ -z "$IsTMP" ]; then
        cp /root/hello.sh /tmp/hello.sh
        /bin/sh /tmp/hello.sh &
        exit
else
        unlink /hello.sh
        rsync /root/hello.sh /hello.sh
        rm /root/hello.sh
        rm /tmp/hello.sh
fi


while true; do
        sleep 5
        echo "Still Alive"
done

This script works totally well and suits my needs (even though it is a horrendous hack): the script is moved, and re-executed from a temporary place. However, when i pipe the shell script with a tee, just like:

/hello.sh | tee -a /log&

The behaviour is not the same:

This behaviour is the exact same if i replace tee with another binary (e.g. watch,...), so I am wondering if it comes from piping.

Sorry if i am not too clear about my problem. Thanks in advance.

Upvotes: 2

Views: 327

Answers (1)

Armali
Armali

Reputation: 19395

When i try to kill tee, the temporary copy is automatically killed after a few seconds, without entering the infinite loop

That's not the case. The script is entering the infinite loop, the few seconds are the five the sleep 5 in the loop pauses, and then it is killed by the signal SIGPIPE (Broken pipe) because it tries to echo "Still Alive" to the pipe which is closed on the read end since tee has been killed.

There is no link between tee and the second instance

That's not the case. There is a link, namely the pipe, the write end of which is the standard output of the parent as well as (inherited) the child shell script, and the read end is the standard input of tee. You can see this if you look at ls -l /proc/pid/fd, where pid is the process id of the script's shell on the one hand, and of tee on the other.

Upvotes: 0

Related Questions