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: Andreas Kusalananda Kähäri
Subject: Re: Why doesn't $? catch the exit status on interrupt?
Date: Thu, 28 Jul 2022 11:30:26 +0200

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'


> 
> 
> 
> 
> However, if I do the same thing in a script, it does not work.
> 
> $ cat test.sh
> #!/bin/bash
> trap 'echo status: $?' EXIT
> sleep 3
> $ ./test.sh
> ^Cstatus: 0
> 
> 
> 
> 
> I think I am terribly missing something,
> but why does the latter show 0 instead of 130?
> 
> 
> -- 
> Best Regards
> Masahiro Yamada

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



reply via email to

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