Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Bash's read abort after trapping interrupt?

Tags:

bash

signals

Consider:

$ cat b.sh
#!/bin/bash

trap 'echo $$ was interrupted' INT
read foo
echo done
$ ./b.sh
^C27104 was interrupted
^C27104 was interrupted
^C27104 was interrupted
done
$ 

(ctrl-c was hit 3 times, followed by ctrl-d)

I'd like the read to abort after execution of the trap. Is there a clean way to make that happen?

like image 715
William Pursell Avatar asked Dec 07 '17 18:12

William Pursell


1 Answers

Seems like not interrupting immediately is a Bash non-POSIX extension (see read_builtin in read.def of Bash builtin source (look for posixly_correct)).

You can override this behavior, and exit on the first Ctrl+C by forcing POSIX behavior for read (by setting the POSIXLY_CORRECT environment variable):

#!/bin/bash
trap 'echo $$ was interrupted' INT
POSIXLY_CORRECT=1 read foo
echo done
like image 74
randomir Avatar answered Nov 02 '22 16:11

randomir