程式扎記: [Linux 常見問題] What is the Linux equivalent to DOS pause?

標籤

2016年4月23日 星期六

[Linux 常見問題] What is the Linux equivalent to DOS pause?

Source From Here
Question
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?

How-To
You can leverage read command in bash. For example:
// The -r option removes a completion specification
// -p: Display readline function names and bindings in such a way that they can be re-read.
// read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

# read -n2 -r -p "Press any key to continue..." key // Read two character from input and saved to environment variable key
Press any key to continue...a
# echo $key
a

The -n2 specifies that it only waits for two characters. 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.

f 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  


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!