[linux] What is the Linux equivalent to DOS pause?

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?

This question is related to linux bash shell

The answer is


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

I use these ways a lot that are very short, and 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 scripts that run in a loop until the user presses Enter.

Commands

  • Enter solution

    read -rsp $'Press enter to continue...\n'
    
  • Escape solution (with -d $'\e')

    read -rsp $'Press escape to continue...\n' -d $'\e'
    
  • Any key solution (with -n 1)

    read -rsp $'Press any key to continue...\n' -n 1 key
    # echo $key
    
  • Question with preselected choice (with -ei $'Y')

    read -rp $'Are you sure (Y/n) : ' -ei $'Y' key;
    # echo $key
    
  • Timeout solution (with -t 5)

    read -rsp $'Press any key or wait 5 seconds to continue...\n' -n 1 -t 5;
    
  • Sleep enhanced alias

    read -rst 0.5; timeout=$?
    # echo $timeout
    

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 escappe 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 $?


I use these ways a lot that are very short, and 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 scripts that run in a loop until the user presses Enter.

Commands

  • Enter solution

    read -rsp $'Press enter to continue...\n'
    
  • Escape solution (with -d $'\e')

    read -rsp $'Press escape to continue...\n' -d $'\e'
    
  • Any key solution (with -n 1)

    read -rsp $'Press any key to continue...\n' -n 1 key
    # echo $key
    
  • Question with preselected choice (with -ei $'Y')

    read -rp $'Are you sure (Y/n) : ' -ei $'Y' key;
    # echo $key
    
  • Timeout solution (with -t 5)

    read -rsp $'Press any key or wait 5 seconds to continue...\n' -n 1 -t 5;
    
  • Sleep enhanced alias

    read -rst 0.5; timeout=$?
    # echo $timeout
    

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 escappe 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 $?


This worked for me on multiple flavors of Linux, where some of these other solutions did not (including the most popular ones here). I think it's more readable too...

echo Press enter to continue; read dummy;

Note that a variable needs to be supplied as an argument to read.


This worked for me on multiple flavors of Linux, where some of these other solutions did not (including the most popular ones here). I think it's more readable too...

echo Press enter to continue; read dummy;

Note that a variable needs to be supplied as an argument to read.


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.


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.


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.


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.


read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

If you just need to pause a loop or script, and you're happy to press Enter instead of any key, then read on its own will do the job.

do_stuff
read
do_more_stuff

It's not end-user friendly, but may be enough in cases where you're writing a quick script for yourself, and you need to pause it to do something manually in the background.


If you just need to pause a loop or script, and you're happy to press Enter instead of any key, then read on its own will do the job.

do_stuff
read
do_more_stuff

It's not end-user friendly, but may be enough in cases where you're writing a quick script for yourself, and you need to pause it to do something manually in the background.


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 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!


Try this:

function pause(){
   read -p "$*"
}

Try this:

function pause(){
   read -p "$*"
}

Try this:

function pause(){
   read -p "$*"
}

Try this:

function pause(){
   read -p "$*"
}

Yes to using read - and there are a couple of tweaks that make it most useful in both cron and in the terminal.

Example:

time rsync (options)
read -n 120 -p "Press 'Enter' to continue..." ; echo " "

The -n 120 makes the read statement time out after 2 minutes so it does not block in cron.

In terminal it gives 2 minutes to see how long the rsync command took to execute.

Then the subsequent echo is so the subsequent bash prompt will appear on the next line.

Otherwise it will show on the same line directly after "continue..." when Enter is pressed in terminal.


Yes to using read - and there are a couple of tweaks that make it most useful in both cron and in the terminal.

Example:

time rsync (options)
read -n 120 -p "Press 'Enter' to continue..." ; echo " "

The -n 120 makes the read statement time out after 2 minutes so it does not block in cron.

In terminal it gives 2 minutes to see how long the rsync command took to execute.

Then the subsequent echo is so the subsequent bash prompt will appear on the next line.

Otherwise it will show on the same line directly after "continue..." when Enter is pressed in terminal.


Questions with linux tag:

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt? How to post raw body data with curl? Copy Files from Windows to the Ubuntu Subsystem How to use local docker images with Minikube? Can Windows Containers be hosted on linux? gradlew command not found? ssh connection refused on Raspberry Pi Composer: file_put_contents(./composer.json): failed to open stream: Permission denied Curl : connection refused boto3 client NoRegionError: You must specify a region error only sometimes gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now sudo: docker-compose: command not found How to upgrade pip3? How can I remove jenkins completely from linux Linux Command History with date and time MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded" What is difference between arm64 and armhf? How to redirect output of systemd service to a file Retrieve last 100 lines logs Failed to find Build Tools revision 23.0.1 Run an Ansible task only when the variable contains a specific string What does `set -x` do? How to edit a text file in my terminal Starting a shell in the Docker Alpine container How to run SUDO command in WinSCP to transfer files from Windows to linux Fail during installation of Pillow (Python module) in Linux How to install Android SDK on Ubuntu? How do I delete virtual interface in Linux? What is the default root pasword for MySQL 5.7 Docker command can't connect to Docker daemon How to find files modified in last x minutes (find -mmin does not work as expected) Can I use Homebrew on Ubuntu? Pycharm and sys.argv arguments Ubuntu: OpenJDK 8 - Unable to locate package Fork() function in C Amazon Linux: apt-get: command not found Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable Ubuntu: Using curl to download an image Docker error response from daemon: "Conflict ... already in use by container" Curl command without using cache Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

Questions with bash tag:

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal? Copy Files from Windows to the Ubuntu Subsystem Docker: How to use bash with an Alpine based docker image? How to print / echo environment variables? Passing bash variable to jq gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now How to check if an environment variable exists and get its value? docker entrypoint running bash script gets "permission denied" Copy Paste in Bash on Ubuntu on Windows How to set env variable in Jupyter notebook How do I disable Git Credential Manager for Windows? How to set aliases in the Git Bash for Windows? MINGW64 "make build" error: "bash: make: command not found" Disable beep of Linux Bash on Windows 10 What does `set -x` do? psql: command not found Mac How do I use a regex in a shell script? nodemon not working: -bash: nodemon: command not found How to open google chrome from terminal? Get Environment Variable from Docker Container How to find files modified in last x minutes (find -mmin does not work as expected) How to pass arguments to Shell Script through docker run How to run C program on Mac OS X using Terminal? Curl command without using cache Running a script inside a docker container using shell script Creating an array from a text file in Bash Bash checking if string does not contain other string How to check if a Docker image with a specific tag exist locally? How do I edit $PATH (.bash_profile) on OSX? Raise error in a Bash script how to wait for first command to finish? I just assigned a variable, but echo $variable shows something else What do $? $0 $1 $2 mean in shell script? How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script How can I remount my Android/system as read-write in a bash script using adb? How to get ip address of a server on Centos 7 in bash Changing an AIX password via script? How to remove last n characters from a string in Bash? Difference between ${} and $() in Bash List file using ls command in Linux with full path

Questions with shell tag:

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied" Interactive shell using Docker Compose How do I use a regex in a shell script? How to pass arguments to Shell Script through docker run Can pm2 run an 'npm start' script Running a script inside a docker container using shell script shell script to remove a file if it already exist Run a command shell in jenkins Raise error in a Bash script I just assigned a variable, but echo $variable shows something else What do $? $0 $1 $2 mean in shell script? How to sort a file in-place How to get a shell environment variable in a makefile? How to read a .properties file which contains keys that have a period character using Shell script Run multiple python scripts concurrently how to check which version of nltk, scikit learn installed? Changing an AIX password via script? Loop through a comma-separated shell variable How to use execvp() List file using ls command in Linux with full path How to use su command over adb shell? Display curl output in readable JSON format in Unix shell script How to check the exit status using an if statement How to solve ADB device unauthorized in Android ADB host device? Redirect echo output in shell script to logfile adb shell su works but adb root does not Run Python script at startup in Ubuntu Copy multiple files from one directory to another from Linux shell Relative paths based on file location instead of current working directory How to Batch Rename Files in a macOS Terminal? Speed up rsync with Simultaneous/Concurrent File Transfers? Multi-line string with extra space (preserved indentation) How to set child process' environment variable in Makefile Get MAC address using shell script How to force 'cp' to overwrite directory instead of creating another one inside? Multiple conditions in if statement shell script How do I change file permissions in Ubuntu How to get key names from JSON using jq Bash: Echoing a echo command with a variable in bash How/When does Execute Shell mark a build as failure in Jenkins? Shell Script: How to write a string to file and to stdout on console?