Bash confirmation won't wait for user input

筅森魡賤 提交于 2020-06-12 08:02:46

问题


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"

回答1:


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



回答2:


The original question has the important part missing and it is my fault not making it very clear in very first place. It became apparent after @NahuelFouilleul's comment. The confirmation/question prompt was not waiting for user to hit a key. The reason was because my bash script was being called by a git hook. Things seem to be done in slightly different way in such cases. The solution is below but the original answer is here.

#!/bin/bash

exec < /dev/tty

while true; do
    read -p "Accepting the offer? (y/n) " answer

    if [[ $answer =~ ^[Yy]$ ]] ;
    then
        echo "Accepted"
    else
        echo "Not accepted"
    fi

    break
done



回答3:


Try this:

echo -n "Continue  (y/n)?"
read CONT
if [ "$CONT" = "n" ]
then
  echo "NO"
else
  echo "YES"
fi

the echo -n means no newline



来源:https://stackoverflow.com/questions/48640615/bash-confirmation-wont-wait-for-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!