William Pursell
William Pursell

Reputation: 212188

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

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?

Upvotes: 8

Views: 384

Answers (1)

randomir
randomir

Reputation: 18687

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

Upvotes: 9

Related Questions