Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Why doesn't the command below exit? Rather than exit, the loop runs indefinitely.

While I discovered this behavior using a more complex setup, the simplest form of the command reduces to the following.

Does not exit:

while /usr/bin/true ; do echo "ok" | cat ; done | exit 1

There are no typos above. Each '|' is a pipe. The 'exit 1' stands in for another process that ran and exited.

I expect the "exit 1" to cause a SIGPIPE on the while loop (write on a pipe with no reader) and for the loop to break out. But, the loop continues running.

Why doesn't the command stop?

share|improve this question
    
zsh exits normally. –  Braiam Jan 4 at 14:27

1 Answer 1

up vote 11 down vote accepted

It is due to a choice in implementation.

Running the same script on Solaris with ksh93 produces a different behavior:

$ while /usr/bin/true ; do echo "ok" | cat ; done | exit 1
cat: write error [Broken pipe]

What triggers the issue is the inner pipeline, without it, the loop exits whatever the shell/OS:

$ while /usr/bin/true ; do echo "ok" ; done | exit 1
$

cat is getting a SIGPIPE signal under bash but the shell is iterating the loop anyway.

Process 5659 suspended
[pid 28801] execve("/bin/cat", ["cat"], [/* 63 vars */]) = 0
[pid 28801] --- SIGPIPE (Broken pipe) @ 0 (0) ---
Process 5659 resumed
Process 28801 detached
Process 28800 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
Process 28802 attached
Process 28803 attached
[pid 28803] execve("/bin/cat", ["cat"], [/* 63 vars */]) = 0
Process 5659 suspended
[pid 28803] --- SIGPIPE (Broken pipe) @ 0 (0) ---
Process 5659 resumed
Process 28803 detached
Process 28802 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
Process 28804 attached
Process 28805 attached (waiting for parent)
Process 28805 resumed (parent 5659 ready)
Process 5659 suspended
[pid 28805] execve("/bin/cat", ["cat"], [/* 63 vars */]) = 0
[pid 28805] --- SIGPIPE (Broken pipe) @ 0 (0) ---
Process 5659 resumed
Process 28805 detached
Process 28804 detached
--- SIGCHLD (Child exited) @ 0 (0) ---

Bash documentation states:

The shell waits for all commands in the pipeline to terminate before returning a value.

Ksh documentation states:

Each command, except possibly the last, is run as a separate process; the shell waits for the last command to terminate.

POSIX states:

If the pipeline is not in the background (see Asynchronous Lists), the shell shall wait for the last command specified in the pipeline to complete, and may also wait for all commands to complete.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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