我需要在 shell 脚本上暂停一下,以显示警告,然后再继续。例如,在 DOS 上,它如下所示:
doit.bat:
[...]
echo 'Are you sure? Press Ctrl-C to abort, enter to continue.'
pause
[...]
我如何在 bash 上执行此操作?目前,sleep 命令似乎可以解决问题,并且足够简单,但并不是真正的想法:
doit.sh
[...]
echo 'Are you sure? Press Ctrl-C to abort.'
sleep 3
[...]
答案1
类似于
echo -n "prompt" #'-n' means do not add \n to end of string
read # No arg means dump next line of input
答案2
read -p "Press any key to continue or CTRL-C to abort"
在我的脚本中,在 14.04 下运行良好。正如 @Lekensteyn 在上面的评论中所述,似乎从 12.04.4 开始就一直如此。“帮助阅读”页面指出:
-p prompt output the string PROMPT without a trailing newline before
attempting to read
答案3
最简单的等待停止脚本的方法是kill -STOP $$
从脚本中调用:暂停后,脚本将在收到-CONT 信号后继续工作。
#!/bin/bash
echo "$0 stopping now"
kill -STOP $$
echo "$0 continues its work"
答案4
echo "press enter to continue"
read unusedVariable
echo "running these 3 lines in .sh file, this echo will never be seen, unless you have a really slow computer"
将这 3 行放入 .sh 文件中并运行它