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 -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:
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 -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:
- read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
- if [ "$?" -eq "0" ]; then
- echo 'A key was pressed.'
- else
- echo 'No key was pressed.'
- fi
沒有留言:
張貼留言