Bash 确认不会等待用户输入

Bash confirmation won't wait for user input

我正在尝试使用 bash 脚本实现确认提示,但出于某种原因,提示不会等待用户输入。我已经尝试了很多例子,但到目前为止还没有运气。如果有任何不同,我正在使用 MacOS。

只是我试过的几个例子(所有从其他答案复制粘贴):

#!/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

这甚至没有提示任何内容:

#!/bin/bash
read -n 1 -s -r -p "Press any key to continue"

试试这个:

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

echo -n 表示没有换行符

更改为评论中的回答:在 commit-msg 挂钩中,标准输入似乎已关闭,确实可以通过添加以下命令来检查

ls -l /dev/fd/

这给出了

... 0 -> /dev/null

this post

所述
exec 0< /dev/tty

将标准输入恢复到 tty,另一种解决方案注意到标准输出和错误仍然重定向到 tty

exec 0<&1

原题漏了重要的部分,一开始没说清楚是我的错。在@NahuelFouilleul 发表评论后,这一点变得很明显。 confirmation/question 提示没有等待用户按下一个键。原因是因为 bash 脚本被 git 挂钩调用。在这种情况下,事情似乎以略有不同的方式完成。解决方案如下,但原始答案是 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