help-bash
[Top][All Lists]
Advanced

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

Re: Why doesn't $? catch the exit status on interrupt?


From: Masahiro Yamada
Subject: Re: Why doesn't $? catch the exit status on interrupt?
Date: Thu, 28 Jul 2022 23:30:18 +0900

On Thu, Jul 28, 2022 at 6:36 PM Andreas Kusalananda Kähäri
<andreas.kahari@abc.se> wrote:
>
> On Thu, Jul 28, 2022 at 04:55:23PM +0900, Masahiro Yamada wrote:
> > Hi.
> >
> > I want to do something in the EXIT trap
> > when a command fails (including interruption).
> >
> >
> > If I pass the code to "bash -c", it works as I expect.
> > (If I press Ctrl-C, I see 130).
> >
> > $ bash -c "trap 'echo status: $?' EXIT; sleep 3"
> > ^Cstatus: 130
>
> In your command above, $? is replaced by the exit status of whatever
> command you most recently ran.  This is due to using $? in a
> double-quoted string.
>
> Try instead with
>
>         bash -c 'trap "echo status: \$?" exit; sleep 3'

Ah, you are right.  Quotation was wrong in the first example,
so $? was expanded by the interactive shell instead of the
subshell.




So, is there any way to know that it was interrupted?


More experiments.

$ bash -c 'trap "echo status: \$?" EXIT; true; sleep 3'
^Cstatus: 0

$ bash -c 'trap "echo status: \$?" EXIT; false; sleep 3'
^Cstatus: 1


So, if I interrupt 'sleep 3' by pressing Ctrl-C,
$? contains the exit status of the command running before.
(In this case, the exit status of 'true' or 'false')



In contrast, if I do something similar in an interactive shell,
$? contains 130.


$ false
$ sleep 3
^C
$ echo $?
130



How can I get 130 in script mode?


-- 
Best Regards
Masahiro Yamada



reply via email to

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