[关闭]
@haokuixi 2015-05-08T13:03:11.000000Z 字数 2468 阅读 2195

What is the Linux equivalent to DOS pause?

linux shell


I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the "pause" command. Is there a Linux equivalent I can use in my script?


read does this:

user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$ 

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

If you are using bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

  1. read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
  2. if [ "$?" -eq "0" ]; then
  3. echo 'A key was pressed.'
  4. else
  5. echo 'No key was pressed.'
  6. fi

I use a lot these ways that are very short, they are like @theunamedguy and @Jim solutions but with timeout and silent mode in addition.
I especially love the last case and use it in a lot of script that run in loop until the user press Enter.

Commands

Explanation

-r specifies raw mode, which don't allow combined characters like \ or ^.

-s specifies silent mode, and because we don't need keyboard output.

-p $'prompt' specifies the prompt, which need to be between $' and ' to let spaces and escaped characters. Be careful, you must put between single quotes with dollars symbol to benefit escaped characters, otherwise you can use simple quotes.

-d $'\e' specifies escape as delimiter charater, so as a final character for current entry, this is possible to put any character but be careful to put a character that the user can type.

-n 1 specifies that it only needs a single character.

-e specifies readline mode.

-i $'Y' specifies Y as initial text in readline mode.

-t 5 specifies a timeout of 5 seconds

key serve in case you need to know the input, in -n1 case, the key that has been pressed.

$? serve to know the exit code of the last program, for read, 142 in case of timeout, 0 correct input. Put $? in a variable as soon as possible if you need to test it after somes commands, because all commands would rewrite $?


Reference:
http://stackoverflow.com/questions/92802/what-is-the-linux-equivalent-to-dos-pause

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注