【发布时间】:2018-07-16 08:59:04
【问题描述】:
我正在尝试使用 bash 脚本实现确认提示,但由于某种原因,提示不会等待用户输入。我已经尝试了很多例子,但到目前为止还没有运气。如果有什么不同,我在 MacOS 上。
只是我尝试的几个例子(所有复制+粘贴来自 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
这甚至不会提示任何内容:
#!/bin/bash
read -n 1 -s -r -p "Press any key to continue"
【问题讨论】:
-
不清楚。什么不工作,什么是预期行为?
-
1.运行 bash 脚本。 2. 提示用户“你想继续吗?[y/N]” 3. 用户按任意键。 4.如果是“y”,那么做一些事情,否则继续。问题:第 2 步只是在终端上打印消息并在没有提示用户的情况下完成。
-
脚本是如何启动的?
-
它实际上是一个
.git/hooks/commit-msg文件,所以当用户运行git commit -m 'Hello'时,commit-msg会被触发/启动。 -
看到这个答案how-do-i-prompt-the-user-from-within-a-commit-msg-hook,好像标准输入已经关闭了,确实可以加
ls -l /dev/fd/看:0 -> /dev/null,另一种解决方案,可能是exec 0
标签: bash githooks pre-commit-hook