rub*_*o77 100 bash control-flow
如何在用户按下之前停止 bash 脚本Space?
我想在我的脚本中提出问题
按空格继续或CTRL+C退出
然后脚本应该停止并等到按下空格键。
小智 78
您可以使用read:
read -n1 -s -r -p $'Press space to continue...\n' key
if [ "$key" = ' ' ]; then
# Space pressed, do something
# echo [$key] is empty when SPACE is pressed # uncomment to trace
else
# Anything else pressed, do whatever else.
# echo [$key] not empty
fi
Run Code Online (Sandbox Code Playgroud)
将' '上面的空格替换为''Enter 键$'\t'和 Tab 键。
slm*_*slm 55
在此 SO Q&A 中讨论的方法可能是替代pause您在 Windows 上处理 BAT 文件时习惯的行为的最佳选择。
$ read -rsp $'Press any key to continue...\n' -n1 key
Run Code Online (Sandbox Code Playgroud)
在这里我运行上面的,然后简单地按任意键,在这种情况下是D键。
$ read -rsp $'Press any key to continue...\n' -n1 key
Press any key to continue...
$
Run Code Online (Sandbox Code Playgroud)
rub*_*o77 11
您可以pause为它创建一个函数,以便在脚本中的任何地方使用,例如:
#!/bin/bash
pause(){
while read -r -t 0.001; do :; done # dump the buffer
read -n1 -rsp $'Press any key to continue or Ctrl+C to exit...\n'
}
echo "try to press any key before the pause, it won't work..."
sleep 5
pause
echo "done"
Run Code Online (Sandbox Code Playgroud)
hold=' '
printf "Press 'SPACE' to continue or 'CTRL+C' to exit : "
tty_state=$(stty -g)
stty -icanon
until [ -z "${hold#$in}" ] ; do
in=$(dd bs=1 count=1 </dev/tty 2>/dev/null)
done
stty "$tty_state"
Run Code Online (Sandbox Code Playgroud)
现在打印一个没有尾随换行符的提示,CTRL+C可靠地处理,stty只在必要时调用,并将控制 tty 恢复到stty找到它的状态。查看man stty有关如何明确控制回声、控制字符等的信息。
你也可以这样做:
printf "Press any key to continue or 'CTRL+C' to exit : "
(tty_state=$(stty -g)
stty -icanon
LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
stty "$tty_state"
) </dev/tty
Run Code Online (Sandbox Code Playgroud)
你可以用ENTER, 没有[测试],也没有stty像:
sed -n q </dev/tty
Run Code Online (Sandbox Code Playgroud)
这是一种同时适用于bash和 的方法zsh,可确保终端的 I/O:
# Prompt for a keypress to continue. Customise prompt with $*
function pause {
>/dev/tty printf '%s' "${*:-Press any key to continue... }"
[[ $ZSH_VERSION ]] && read -krs # Use -u0 to read from STDIN
[[ $BASH_VERSION ]] && </dev/tty read -rsn1
printf '\n'
}
export_function pause
Run Code Online (Sandbox Code Playgroud)
把它放在你.{ba,z}shrc的大正义中!
这是按空格键继续(而不是回车)的简单解决方案
read -r -s -d ' '
Run Code Online (Sandbox Code Playgroud)
这将等到您按下空格键。是的,只有空格键,按回车键也不会中断。