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  


沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...