Questions on the behavior of CTLR+C and trap when job control is enabled
From:
Grégory Pakosz
Subject:
Questions on the behavior of CTLR+C and trap when job control is enabled/disabled
Date:
Tue, 3 Jun 2025 13:41:03 +0200
Hello all,
I'm using Bash 5.2 on macOS:
-----
bash-5.2$ bash -version
GNU bash, version 5.2.37(1)-release (aarch64-apple-darwin23.4.0)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
-----
I reached out to #bash on Libera about the following little "loop.sh"
test program and they advised me to post to this list:
-----
#!/usr/bin/env bash
# https://paste.debian.net/hidden/3e73a580/
_int() {
printf '\nBEGIN TRAP\n'
interrupted=true
trap - INT
printf 'END TRAP\n'
}
loop() {
local interrupted=false
trap _int INT
printf 'BEFORE WHILE LOOP\ninterrupted: %s\n' "$interrupted"
while ! "$interrupted"; do
echo "interrupted: $interrupted"
printf 'interrupted: %s\n' "$interrupted"
sleep 0.5
done
printf 'AFTER WHILE LOOP\ninterrupted: %s\n' "$interrupted"
"$interrupted" && kill -s INT -- "$$"
}
if [ -n "$BASH_VERSION" ] && [ "${BASH_SOURCE[0]}" = "$0" ]; then
loop "$@"
fi
-----
• When I execute the loop.sh script, hitting CTRL+C ends up running
the _int() function:
-----
bash-5.2$ ./loop.sh
BEFORE WHILE LOOP
interrupted: false
interrupted: false
interrupted: false
interrupted: false
interrupted: false
^C
BEGIN TRAP
END TRAP
AFTER WHILE LOOP
interrupted: true
-----
• When I source loop.sh then execute the loop() function, hitting
CTRL+C interrupts the script but the _int() function is not executed
which also means the trap for SIGINT is not cleared out:
-----
bash-5.2$ source ./loop.sh
bash-5.2$ loop
BEFORE WHILE LOOP
interrupted: false
interrupted: false
interrupted: false
interrupted: false
interrupted: false
^C
bash-5.2$ trap
trap -- '_int' SIGINT
-----
• When I disable job control and launch the loop() function again, it
behaves the same as when I execute the script:
-----
bash-5.2$ set +m
bash-5.2$ loop
BEFORE WHILE LOOP
interrupted: false
interrupted: false
interrupted: false
interrupted: false
interrupted: false
interrupted: false
interrupted: false
^C
BEGIN TRAP
END TRAP
AFTER WHILE LOOP
interrupted: true
bash-5.2$ trap
bash-5.2$
-----
Can someone please explain what's going on here?
How does job control affect whether traps are being executed?
Thank you,
Grégory