Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tee resets exit status is always 0

Tags:

bash

shell

wait

tee

I have a short script like this:

#!/bin/bash
<some_process> | tee -a /tmp/some.log  &
wait $(pidof <some_process_name>)
echo $?

The result is always 0, irrespective of the exit status of some_process.

I know PIPESTATUS can be used here, but why does tee break wait?

like image 626
Jeryl Vaz Avatar asked Sep 03 '25 13:09

Jeryl Vaz


1 Answers

Well, this is something that, for some peculiar reason, the docs don't mention. The code, however, does:

int wait_for (pid) { /*...*/
/* If this child is part of a job, then we are really waiting for the
job to finish. Otherwise, we are waiting for the child to finish. [...] */

if (job == NO_JOB)
  job = find_job (pid, 0, NULL);

So it's actually waiting for the whole job, which, as we know, normally yields the exit status of the last command in the chain.

To make matters worse, $PIPESTATUS can only be used with the last foreground command.

You can, however, utilize $PIPESTATUS in a subshell job, like this:

(<some_process> | tee -a /tmp/some.log; exit ${PIPESTATUS[0]}) &
# somewhere down the line:
wait %%<some_process>
like image 150
Yam Marcovic Avatar answered Sep 05 '25 04:09

Yam Marcovic