我有一个Bash shell脚本,我想暂停执行,直到用户按下一个键。在DOS中,这可以通过pause命令轻松完成。在我的脚本中是否有一个Linux等效程序?


当前回答

这个函数在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

把它放进你的。{ba,z}shrc代表大正义!

其他回答

这在多种Linux版本上都适用,而其他一些解决方案(包括这里最受欢迎的解决方案)则不适用。我认为它也更有可读性…

echo Press enter to continue; read dummy;

注意,需要将变量作为参数提供以供读取。

试试这个:

function pause(){
   read -p "$*"
}

不带任何参数的读取将只在按enter键时继续。 如果您按下任何键,DOS暂停命令将继续。如果您想要这种行为,请使用read -n1。

我已经建立了一个小程序来实现暂停命令在Linux。我已经在我的GitHub回购上传了代码。

要安装它,

git clone https://github.com/savvysiddharth/pause-command.git
cd pause-command
sudo make install

安装后,您现在可以使用类似于在windows中所做的暂停命令。

它还支持可选的自定义字符串,如read。

例子:

pause "Pausing execution, Human intervention required..."

使用这个,C/ c++程序使用像system("pause");现在与linux兼容。

这样,按下除ENTER以外的任何键仍然会转到新行

read -n1 -r -s -p "Press any key to continue..." ; echo

它比Windows暂停更好,因为你可以改变文本使它更有用

read -n1 -r -s -p "Press any key to continue... (cant find the ANY key? press ENTER) " ; echo