5

On Windows in a git commit-msg I want to run following script:

MSG="$1"
if ! grep -s -qE "#[0-9]" "$MSG";then
    exec < /dev/tty
    cat "$MSG"
    echo "Your commit message does not contain a reference to a work item. Continue? [y/n]"
    read -s -n 1 sure
    if [[ $sure == "y" ]]; then
        exit 0
    else
        echo "Aborting commit..."
        exit 1
    fi
fi

It runs fine when I use Git extensions.

But when I want to commit directly from Visual Studio (Team Explorer or Git Changes) an error with following message is occurring:

Your git-hook, '.git/hooks/commit-msg' (line 23) is not supported, likely because it expects interactive console support./r/nSee your administrator for additional assistance.

My question: Is there a possibility to check, whether exec < /dev/tty can be executed? Otherwise I would just print a corresponding message.

Thanks in advance.

Peter
  • 743
  • 5
  • 26

1 Answers1

7

You can use if [ -t 1 ] or if [ -t 2 ] to test if you are in a pipe or in a terminal.

if [ -t 1 ]; then    # or if [ -t 2 ]
   # do interactive stuff
else
   # non-interactive variant
fi

Ref: How to detect if my shell script is running through a pipe?

EDIT: OP reports that [ -t 1 ] in my original answer did not work, but that [ -t 2 ] does. The first tests for stdout going to the tty, while the second tests for stderr going to the tty. In this case, I'm guessing that both Git Extensions and Visual Studio capture the scripts's stdout, but Git Extensions sends stderr to the tty while Visual Studio also captures it.

joanis
  • 10,635
  • 14
  • 30
  • 40
  • Thanks for your answer. I tried that already before without success. According to that test it is always in the #non-interactive variant. But at least with git extensions, I have the possibility to interact – Peter Feb 07 '19 at 07:52
  • I suppose the problem is that when launched from Git extensions, the output is probably still being piped. Have you also tried with `[ -t 0 ]` and `[ -t 2 ]`? I imagine they won't work either if `[ -t 1 ]` doesn't, but you never know. How about testing the return code from the `exec`? That ought to fail, in which case something like `if exec < /dev/tty; then interactive variant; else non-interactive variant; fi` might work. – joanis Feb 07 '19 at 21:50