0

I'm trying to do a cleanup using trap command. The safe_cancel function is being called when I hit a Ctrl + C but the script isn't being exited. I have to use Ctrl + Z to suspend the script and then kill.

The foo is another script I have in my PATH which returns an exit 1 if it receives an invalid argument.

What am I lacking or doing wrong in this script?

#!/bin/bash

safe_cancel () {
    echo "Cancelling..."
    # do some cleanup here
    exit 1
}

trap safe_cancel 1

while true; do
    read -p "Choose an option: " someOption < /dev/tty
    foo $someOption
    if [[ $? == 0 ]]
    then
        break
        exit 0
    fi
done

Additional details:

I'm writing this script for a Git hook. Apparently, git hooks aren't exactly expecting a standard in/out so I have to explicitly use /dev/tty

Edit:

When using this as part of a git hook, I'm receiving the error
read: read error: 0: Input/output error
and it's an infinite loop

niverg
  • 31
  • 2
  • If you have an IO error reading from the redirected FD, the clear meaning is that you don't have TTY access from that process. `/dev/tty` only works from processes with a controlling TTY. – Charles Duffy Mar 10 '20 at 13:43
  • BTW, see [Why is testing "$?" to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/q/36313216/14122) – Charles Duffy Mar 10 '20 at 13:45
  • 1
    If you don't have a controlling TTY, that also would explain why ctrl+c is not delivering a signal (so the script interpreter wouldn't have any way of knowing that you typed it). – Charles Duffy Mar 10 '20 at 13:53
  • BTW, consider putting an `|| exit` on your `read` command to make the loop no longer infinite. – Charles Duffy Mar 10 '20 at 19:06

1 Answers1

2

Signal 1 is SIGHUP, which is raised if the terminal goes away, for example because you were connected from a remote machine and your session was interrupted because the network disconnected. When you press Ctrl+C, this sends SIGINT.

trap safe_cancel HUP INT

This may or may not be related to the error you get with Git.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254