Bash确认不会等待用户输入 [英] Bash confirmation won't wait for user input

查看:107
本文介绍了Bash确认不会等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

推荐答案

最初的问题缺少重要的部分,这是我的错,但我一开始并没有说清楚.在@NahuelFouilleul的评论之后,这一点变得显而易见.确认/问题提示不是在等待用户敲击按键.原因是因为我的bash脚本被git钩子调用.在这种情况下,事情似乎以略有不同的方式完成.解决方案在下面,但原始答案是这里.

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

这篇关于Bash确认不会等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆