On Fri, Sep 21, 2018 at 01:23:57PM +0200, esori...@gsyc.urjc.es wrote: > The man page of bash (Special Parameters section) says: > > ? expands to the exit status of the most > recently executed foreground pipeline. > > Nevertheless, background commands also modify the > value of this variable.
This is incorrect. The exit status of a background command can only be retrieved by calling "wait" (or if the background command itself chooses to write the forthcoming exit status to stdout, or to a file, etc.). > Example: > > esoriano@omac:~$ false > esoriano@omac:~$ sleep 2 & > (wait 3 seconds) > esoriano@omac:~$ echo $? > 0 > esoriano@omac:~$ > > In this example, the most recently executed foreground > command is false, so the value of $? should be 1. Under "Lists": If a command is terminated by the control operator &, the shell exe‐ cutes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. You're seeing the status from the creation of the background job (which is always 0), not from its completion. Compare: wooledg:~$ (sleep 3; exit 47) & pid=$! [1] 19112 wooledg:~$ echo $? 0 wooledg:~$ [1]+ Exit 47 ( sleep 3; exit 47 ) wooledg:~$ echo $? 0 wooledg:~$ wait $pid; echo $? 47 Even after the background job completes, its exit status is never propagated into the foreground shell's $? parameter. The only way to retrieve the status is with a wait command which is given a PID or a job specifier.