网站首页 > 基础教程 正文
当您使用bash脚本时,是否有类似于MSDOS批处理脚本中的“PAUSE”命令,以提示用户按任意键继续执行下一步操作?以下是几种实现方法:
- 使用read命令等待用户按回车键继续执行下一步操作:
# Bash
read -p "Press [enter] to continue..."
# Bourne
echo "Press [enter] to continue..."
read junk
- 使用read命令等待用户按任意键继续执行下一步操作:
# Bash
read -rsn 1 -p "Press any key to continue..."
有时候您需要等待用户按下任意键才能继续执行下一步操作,但是因为您已经在使用标准输入(stdin),例如使用管道来提供脚本,这时候可以使用Unix的灵活性,将输入重定向到终端:
# Bash
read -rsn 1 -p "Press any key to continue..." < /dev/tty
- 如果您想在一定的时间内等待用户按键,可以使用read命令的-t选项,并在超时后执行相应的操作:
# Bash
printf 'WARNING: You are about to do something stupid.\n'
printf 'Press a key within 5 seconds to cancel.'
if ! read -rsn 1 -t 5
then something_stupid
fi
- 如果您只是想暂停一段时间而不管用户的输入,请使用sleep命令:
echo "The script is tired. Please wait a minute."
sleep 60
- 如果您想在等待用户按键时显示倒计时,请使用以下代码段:
# Bash
# 该函数无法处理多位数的倒计时.
countdown() {
local i
printf %s "$1"
sleep 1
for ((i=$1-1; i>=1; i--)); do
printf '\b%d' "$i"
sleep 1
done
}
printf 'Warning!!\n'
printf 'Five seconds to cancel: '
countdown 5 & pid=$!
if ! read -s -n 1 -t 5; then
printf '\nboom\n'
else
kill "$pid"; printf '\nphew\n'
fi
注意:如果您在交互式shell中测试该代码,将会看到作业控制系统的输出,但在脚本中,不会有任何此类输出。
学习更多shell实用功能
如果您觉得文章内容对你有一点帮助可以关注我,我在头条平台会持续分享更多实用的shell技巧和最佳实践,如果想系统的快速学习shell的各种高阶用法和生产环境避坑指南可以看看《shell脚本编程最佳实践》专栏,专栏里有更多的实用小技巧和脚本代码分享。
猜你喜欢
- 2024-10-12 这个为生信学习打造的开源Bash教程真香!!(目录更新)
- 2024-10-12 Shell 函数(杰哥教你Linux) shell中函数
- 2024-10-12 Linux下程序是怎样执行的 linux怎么执行程序
- 2024-10-12 这几个常用 alias,带你高效做事(下)
- 2024-10-12 Shell脚本:函数语法以及实例讲解 shell脚本入门详解
- 2024-10-12 Linux 之 bash 编程 linux bash-4.1
- 2024-10-12 Bash函数:ucase、lcase:借助perl一键转换字符串为大小或小写
- 2024-10-12 Bash Shell制作菜单3部曲:1简单交互菜单|Linux|运维|嵌入式
- 2024-10-12 bash问题:是否有函数可以返回字符串的长度?
- 2024-10-12 shell脚本编程高级用法和函数,并举例说明
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)