Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash confirmation won't wait for user input

I am trying to implement confirmation prompt with a bash script but for some reason, prompt won't wait for user input. I've tried many examples but no luck so far. I am on MacOS if it makes any difference.

Just a few examples I tried (All copy+paste from other answers in SO):

#!/bin/bash

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

#!/bin/bash

read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
  echo "yaaa";
else
  echo "booo";
fi

#!/bin/bash

while true; do
read -rsn1 input
if [ "$input" = "a" ]; then
    echo "hello world"
fi
done

#!/bin/bash

read -p "Continue (y/n)?" choice
case "$choice" in
  y|Y ) echo "yes";;
  n|N ) echo "no";;
  * ) echo "invalid";;
esac

This doesn't even prompt anything:

#!/bin/bash
read -n 1 -s -r -p "Press any key to continue"
like image 803
BentCoder Avatar asked Mar 11 '26 10:03

BentCoder


1 Answers

Changed to answer from comment : in commit-msg hook it seems standard input is closed, indeed this can be checked adding following command

ls -l /dev/fd/

which gives

... 0 -> /dev/null

as mentioned in this post

exec 0< /dev/tty

will restore standard input to tty, another solution as noticed standard output and error are still redirected to tty

exec 0<&1
like image 128
Nahuel Fouilleul Avatar answered Mar 14 '26 01:03

Nahuel Fouilleul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!