Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this bash script not exit?

Tags:

bash

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"

like image 452
wizurd Avatar asked Mar 15 '23 02:03

wizurd


1 Answers

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.

like image 200
choroba Avatar answered Mar 19 '23 19:03

choroba