Alvaro Cavalcanti
Alvaro Cavalcanti

Reputation: 3078

How to ask for user input in a Git hook?

I have been trying to write a simple bash script as a pre-push hook, in which I check for missing test files when pushing Java code.

The problem is: the read command isn't waiting for user input, it proceed as if no input has been entered.

has_java="git diff --stat --cached origin/master | grep \"src\/main.*\.java\""
has_test="git diff --stat --cached origin/master | grep \"src\/test.*\.java\""

exit_val=0

if eval $has_java; then
    if eval $has_test; then
        :
    else
        echo "*** NO TESTS WERE FOUND WHILE PUSHING JAVA CODE ***"
        read -n1 -p "Do you want to CONTINUE pushing? [Y/n]" doit
        case $doit in  
            n|N) exit_val=1 ;; 
            y|Y) exit_val=0 ;;
            *) exit_val=0 ;;
        esac
    fi
fi

Upvotes: 7

Views: 4042

Answers (1)

Alvaro Cavalcanti
Alvaro Cavalcanti

Reputation: 3078

Git hooks do not use standard input. Thus, one must attach the input from the terminal: dev/tty.

Simply appending the terminal at the end of the command makes it work:

read -n1 -p "Do you want to CONTINUE pushing? [Y/n]" doit < /dev/tty

Upvotes: 19

Related Questions