bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Special parameter ?


From: Greg Wooledge
Subject: Re: Special parameter ?
Date: Fri, 21 Sep 2018 08:57:05 -0400
User-agent: NeoMutt/20170113 (1.7.2)

On Fri, Sep 21, 2018 at 01:23:57PM +0200, address@hidden 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:
> 
> address@hidden:~$ false
> address@hidden:~$ sleep 2 &
>        (wait 3 seconds)
> address@hidden:~$ echo $?
> 0
> address@hidden:~$  
> 
> 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.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]