Home > Software design >  bashs's command behavior about exit pipe exit. `exit 1 | exit 2`
bashs's command behavior about exit pipe exit. `exit 1 | exit 2`

Time:09-16

I am curious about bash's behavior and the exit status of the situation when I enter the command

exit [exit status] | exit [exit status] | .. [repetition of exit and exit status]

it gives me output below. and, then doesn't exits.

Is this an undefined behavior?

bash-3.2$ exit 1 | exit 2
bash-3.2$ echo $? 
2

CodePudding user response:

From the bash man page:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

So, even the first exit will not exit your shell, as it only exits the subshell.

As for the exit codes:

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

You can activate pipefail like this:

$ set -o pipefail
$ exit 1 | exit 2 | exit 0
$ echo $?
2

CodePudding user response:

exit 1 | exit 2 is not sequential but concurrent.

Even if the last command takes STDOUT output from the first command. What is a simple explanation for how pipes work in Bash?

Moreover, each one of those commands is executed in a subshell. So your main shell, where you type commands is not exited.

A piped command is like a whole composition of commands instead of one command after another.

If you want to exit, you can make it sequential exit 1 || exit 2.

Finally, by default, $? is the most recent foreground pipeline exit status. What are the special dollar sign shell variables?

  • Related