bug-bash
[Top][All Lists]
Advanced

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

Re: looking for consistent C-c trap behavior


From: gentoo_eshoes
Subject: Re: looking for consistent C-c trap behavior
Date: Sat, 18 Apr 2020 00:00:59 +0200 (CEST)



Apr 17, 2020, 22:14 by gentoo_eshoes@tutanota.com:

>
>
>
> Apr 17, 2020, 22:02 by dualbus@gmail.com:
>
>> On Fri, Apr 17, 2020 at 12:59 PM gentoo_eshoes--- via Bug reports for
>> the GNU Bourne Again SHell <bug-bash@gnu.org> wrote:
>>
>>>
>>> I've noticed that if I trap SIGINT in a bash script, the behavior when 
>>> encountering C-c depends on whether an external command (eg. 'sleep 100') 
>>> or a builtin command (like 'read -p') was encountered.
>>>
>>> I attach an example script which requires me to press C-c twice to 
>>> interrupt the builtin 'read -p' command, and it only works because I'm 
>>> restoring the trap via 'trap - SIGINT' the first time.
>>>
>>> My goal is to have C-c interrupt and use that exit code (130 most likely) 
>>> to exit with from script, regardless or whether or not the interrupted 
>>> command in the script was an internal or external one.
>>>
>>> How to do?
>>>
Let me put some effort into it: (attached anew script, prev. was had extra 
'sleep 100' which was supposed to be commented out)

To break from the builtin 'read', I have to use C-c twice: the first time I 
restore SIGINT trap so that the second C-c can actually make 'read' break/exit

$ ./sigintread.bash 
Press C-c here...^Cinterrupted sees exit code '0'
^C

Maybe I should paste it rather than attach it, here:

#!/bin/bash

#C-c won't break the builtin read unless default SIGINT trap is restored, thus 
needing two C-c to exit

interrupted() {
    local ec="$?"
    trap - SIGINT  #this restores prev. behaviour, so now another C-c will stop 
'read -rp'
    echo "interrupted sees exit code '$ec'"
    #  exit "$ec"  #this is needed ONLY for when 'sleep' is used and 
interrupted, or else it will continue running and hit 'Normal exit', if used 
with 'read' then it will exit without breaking 'read' thus exit code is 0 
instead of 130 (128+2 aka SIGINT==2)
}

trap interrupted SIGINT
builtin read -rp "Press C-c here..."  #can use 'sleep 100' instead of this 
'read...' here, for testing how the behaviour is different with an external 
command instead of a builtin one.
#sleep 100
#ping 127.0.0.1  #ping will ec=0 on C-c
ec="$?"
echo
echo "Normal exit sees ec=$ec"
exit "$ec"

Attachment: sigintread.bash
Description: Binary data


reply via email to

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