4

Might be a basic question, but I'm not sure why logging would cause this exit function to not work as expected:

#!/bin/bash

function exitFunct
{
  exit 1
}

exitFunct  2>&1 | tee -a /var/tmp/output.txt
echo "You should never see this"

But output is "You should never see this"

1 Answer 1

6

As man bash explains,

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

Therefore, the exit in the function exits just the subshell that runs the function's part of the pipeline.

And also,

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled.

Therefore, you can change the behaviour by prepending

set -eo pipefail

to the script (-e makes your script stop on error). Nonetheless, note that using exit 0 wouldn't end it.

Sign up to request clarification or add additional context in comments.

2 Comments

Which means that the exit in the function is exiting the pipeline-spawned sub-shell and not the parent shell. (Just to make that point clear.)
@wizurd: If you don't want grep to end the script, handle the case in an or: grep ... || echo Nothing found

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.