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?
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:
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
read without any parameters will only continue if you press enter.
The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.
This function works in both bash and zsh, and ensures I/O to the terminal:
# 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
Put it in your .{ba,z}shrc for Great Justice!
This fixes it so pressing any key other than ENTER will still go to a new line
read -n1 -r -s -p "Press any key to continue..." ; echo
it's better than windows pause, because you can change the text to make it more useful
read -n1 -r -s -p "Press any key to continue... (cant find the ANY key? press ENTER) " ; echo
I've built a little program to achieve pause command in Linux. I've uploaded the code on my GitHub repo.
To install it,
git clone https://github.com/savvysiddharth/pause-command.git
cd pause-command
sudo make install
With this installed, you can now use pause command similar to like you did in windows.
It also supports optional custom string like read.
Example:
pause "Pausing execution, Human intervention required..."
Using this, C/C++ programs using statements like system("pause"); are now compatible with linux.