Bash script won't exit on input command

470 views Asked by At

I have a bash script that runs on git post-commit hook. What it does is asking the user for an input and based on input it will trigger another action and exits.

The problem is that it will not exit when the action is run, meaning when for example 0 is inputed npm version patch runs and finished but the script hangs there. Have to manual close it using ctrl+c to exit script.

this is my script:

#!/bin/sh

echo "
Script app versioning started! 
"

exec < /dev/tty

while true; do   
read -p "What version should the project update to? 
    - patch[x.x.1] press 0
    - minor[x.1.x] press 1  
    - major[1.x.x] press 2
    - skip patching press 3
    " answer
    case $answer in
            [0] ) 
            npm version patch ;
            exit 0;;
            [1] ) npm version minor;
            exit 0;;
            [2] ) npm version major;
            exit 0;; 
            [3] ) echo "No version patched";
            exit 0;;
            * ) echo "Please answer 0, 1 or 2.";;
    esac
done

echo "
Script app versioning ended!
"
exit 0

is it due to the redirect from command exec < /dev/tty that for when 0,1 or 2 is inputed and the npm version patch command will break output, so it will just continue without exit 0 been triggered and just hangs? If so how do i fix that? tried to redirect the output back like exec > /dev/tty but not working.

Removing the exec < /dev/tty will run the script and exit but won't wait for my command input.

1

There are 1 answers

0
Zapo On BEST ANSWER

I've managed to fix my script by redirecting back my stdout like this:

#!/bin/sh

echo "
Script app versioning started! 
"

exec < /dev/tty

while true; do   
read -p "What version should the project update to? 
    - patch[x.x.1] press 0
    - minor[x.1.x] press 1  
    - major[1.x.x] press 2
    - skip patching press 3
    " answer
    case $answer in
            [0] ) 
            npm version patch ;
            exit 0;;
            [1] ) npm version minor;
            exit 0;;
            [2] ) npm version major;
            exit 0;; 
            [3] ) echo "No version patched";
            exit 0;;
            * ) echo "Please answer 0, 1 or 2.";;
    esac
done  < "${1:-/dev/stdout}"