How to Wait for User Input in Bash [With 4 Practical Examples]

In Bash, the read command is commonly used for taking user input. Interestingly, it allows the scriptwriter to take pause and wait until the user enters some input or presses any key. Moreover, one can set a timeout using the -t option. We can even take different actions based on different inputs provided by the user. We are going to explore waiting for input Bash and how to effectively utilize this in Bash scripting.

4 Practical Examples of Waiting for User Input Using Bash Script

The read command is the default choice for taking user input in Bash scripting. In the subsequent examples, we are going to discuss how to use the read command to wait for user input and discuss their applications in detail.

1. Wait for Input With “timeout” in Bash

This example demonstrates a Bash script that waits for user input while providing a time limit for response. The script allows users to terminate the program by pressing any key on the keyboard within a 5-second period. Here’s a bash script to wait for input with timeout:

#!/bin/bash

echo "Press any key within 5 seconds"

# Loop until a key is pressed or 5 seconds have elapsed
while true; do
read -t 5 -n 1 key  # Read a single character within a 5-second
if [ $? = 0 ]; then
echo -e "\n$key is pressed. Program Terminated"
exit  # Exit the script if a key is pressed
else
echo "Waiting for a keypress"
fi
done

EXPLANATION

Here, the echo command displays the message “Press any key within 5 seconds”. Later an infinite while loop starts that will continue until explicitly terminated.

The read command is used to read a single user input within 5 seconds. The script checks the exit status using $?. If the exit status is 0, it means that a key was pressed within the 5-seconds timeout and the program terminates displaying the message “$key is pressed. Program Terminated”. If the exit status is not 0, the echo command is used to display the message “Waiting for a keypress”. Finally, the loop continues, waiting for a keypress or until the 5-second timeout is reached.

Pressing any key to terminate with timeoutHere, q is pressed within 5 seconds. So, the program terminates.Pressing any key after first timeout In this case, the program waits for an initial 5 seconds during which the user doesn’t press any key. So, it starts waiting for another 5 seconds. This time the user pressed n, hence the program terminated.

2. Wait for Pressing Any Key in Bash script

This example discusses a Bash script that waits for user input and terminates only when the user types any key in the keyboard. Open a file named anykey.sh & write the following script in the file to wait for user input:

#!/bin/bash

echo "Press any key to terminate the application..."

# Loop until a key is pressed
while true; do
read -rsn1 key  # Read a single character silently
if [[ -n "$key" ]]; then
echo "One key detected. Program terminated."
break  # Exit the loop if a key is pressed
fi
done

EXPLANATION

The echo command displays the message “Press any key to terminate the application…”. Later an infinite while loop starts that will continue until explicitly terminated. When a key is pressed, the break statement immediately breaks the loop thus terminating the application.

Press any key to terminate without timeoutThe program terminates as soon as a key is pressed. Note that it doesn’t include Enter key as the exit status of the return key is zero.

3. Wait for Pressing Specific Key in Bash script

Like waiting to press any key, we can write a Bash script that waits for specific input from the user. For instance, the script of this example terminates its execution only when the user presses q. Open a file named specifickey.sh & write the following script to wait for specific user input:

#!/bin/bash
echo "Press the 'q' key to quit..."
while true; do
  # Read a single character from the input
  read -n 1 key
  # Check if the pressed key is 'q'
  if [[ $key == "q" ]]; then
    echo -e "\nProgram is Quitting..."
    break
  else
    echo -e "\nPlease press q to exit."
  fi
done

EXPLANATION

The echo command displays the message  “Press the ‘q’ key to quit…”. Later an infinite while loop starts that will continue until explicitly terminated. The read command is used to read a single input from the user and store the input in a variable namely key. The program terminates if the value stored in key is q. Otherwise, it prints “Please press q to exit”.

Pressing specific key to terminate the programThe program prints Please press q to exit when f is pressed. But it works fine and terminates immediately as soon as q is pressed.

4. Wait for Inputting Specific Key with “timeout” in Bash

This example discusses how we can terminate the execution of a script within a time limit. The program waits for the user to input a specific key to terminate the execution. However, if the user is reluctant to terminate the program inputting that specific key it deliberately terminates itself automatically.

Check the bash script to wait for inputting specific key with timeout:

#!/bin/bash

echo "Program will terminate automatically after 5 seconds."
echo "Press Enter to terminate immediately."
read -t 5
read_exit_status=$?

if [ $read_exit_status = 0 ]; then
echo "You pressed Enter. Program terminated."
else
echo "Timeout occurred. Enter key was not pressed."
fi

EXPLANATION

The echo command displays the message “Program will terminate automatically after 5 seconds.”. Later the read command is used to read a single input from the user within a 5 seconds timeout. $read_exit_status is equal to 0 indicating that enter is pressed within the timeout. So the program terminates before reaching timeout. Otherwise, the program terminates itself automatically when it reaches the timeout of 5 seconds.

Pressing enter key before timeout to terminate in "bash wait for input"The image shows that the program was run two times consecutively. First time it terminates automatically after 5 seconds though the user doesn’t press enter. Second time the user terminated the program by pressing enter before reaching 5 seconds timeout.

2 Practical Applications of Waiting for User Input Using Bash Script

Bash waits for user input and has many real-life applications. This article delves into the creation of interactive menus and the implementation of user confirmation before executing critical actions.  Waiting for user input is the central part of the execution of these applications.

1. Creating Interactive Menu Using Bash Script

In this application, we utilize Bash to create a restaurant menu that waits for user input. Users are presented with four different food items and have the option to select a menu item from the available choices. Here’s a bash code to create an interactive menu to wait for user input:

#!/bin/bash

echo "Program will terminate automatically after 5 seconds."
echo "Press Enter to terminate immediately."
read -t 5
read_exit_status=$?

if [ $read_exit_status = 0 ]; then
echo "You pressed Enter. Program terminated."
else
echo "Timeout occurred. Enter key was not pressed."
fi

EXPLANATION

It reads the user choice while displaying the message “Enter your choice: ” . The case statement offers the user the option of choosing one from different food items. If the user chooses a valid input the program terminates immediately otherwise it displays “Invalid choice. Please try again.” and prompts the menu again.

Pressing valid option in interactive menuHere, user select option A, so the program terminates echoing a message “You selected Pizza. Enjoy your meal !” Pressing invalid option in interactive menuThis time user presses q, which is an invalid option. So the program prompts the options again and waits for taking valid input.

2. User Confirmation Before Critical Action in Bash Script

User confirmation is crucial for major tasks. It adds an extra layer of protection, ensuring users can prevent unintended consequences. For example, before installing potentially risky applications, obtaining user confirmation helps to avoid potential harm to the system and data.

In this Bash script, we create a program that takes user confirmation before deleting all the empty files of the current directory. Open a file & write the following script to accomplish this task:

#!/bin/bash

echo "This script will delete all empty files in the current directory. Are you sure you want to proceed? (y/n)"

while true; do
read -s -n 1 key

case $key in
y|Y)
echo "Deleting empty files..."
find . -type f -empty -print -delete
echo "You pressed $key. Empty files deleted successfully."
exit 0
;;

n|N)
echo "You pressed $key. Operation canceled."
exit 0
;;
*)
echo "Invalid input. Please press 'y' or 'n'."
;;
esac

done

EXPLANATION

It then echoes a message stating that it will delete all empty files in the current directory. At this point, the program waits for user confirmation. If the user presses ‘y’ or ‘Y’, it signifies their intent to proceed. The script executes the find command within a case statement, which deletes all empty files in the current directory. The operation of deleting empty files cancels if the user presses ‘n’ or ‘N’. If the user inputs any other keys, an error message is echoed, indicating invalid input.

Taking user confirmation for performing actionsThis image shows the user enter n. So, the program executes the case statement and cancels the operation of deleting all empty files of the current directory.Invalid input while taking user confirmationThis time user press neither ‘y’ nor ‘n’. Hence it shows a message of invalid input and waits for the user input again.User permission for deleting empty files from current directory for "bash wait for input"Finally, user press ‘y’. So the program proceeds and delete all the empty files from the current directory.

Conclusion

In conclusion, waiting for input in Bash scripts has many practical applications. In some cases, it is important to take input from the user for further execution of the script. Even it may be crucial to continue if the user delays giving input. Hope this article helps you to understand all the basics of implementing how to wait for input in Bash.

People Also Ask

How to pause execution and wait for user input?

The read command can be used to pause execution and wait for user input. -t option of read command is useful to pause a script. -t by default takes second as unit of timeout. The sleep command can also be used for similar purposes.

Wait for complete a background process or user input to terminate?

To terminate a background process based on user input kill command can be used. The read command can take user input. By detecting the input the kill command can terminate the background process.

How to exit if nothing is given in the input wait part?

The easy way to exit if nothing is given in the user input part is by adding a exit statement just after the input section.

Related Articles


<< Go Back to Bash Input | Bash I/O | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

4 thoughts on “How to Wait for User Input in Bash [With 4 Practical Examples]”

  1. Example 4.3 says

    3. Wait for Pressing Specific Key in Bash script
    For instance, the script of this example terminates its execution only when the user presses q.

    Code has: echo “Press any key to terminate the application…”

    Explanation has: The echo command displays the message “Press the ‘q’ key to quit…”.

    Code does not match explanation 😉

    Reply
    • Hi Earl, Thanks for pointing out the mismatch. I have updated the misplaced code and sorry for your inconvenience. Feel free to reach us with your queries about Linux related topics. We are happy to help you. Keep reading. Cheers…

      Reply
  2. Thanks for a clear and complete explanation with examples. I find most other “helpful” articles to be just the opposite. Good work!

    Reply
    • Thanks for your good words. Our motto is to help users with concise examples that clears most of the confusion. Keep exploring our articles and never forget to give a compliment if it is helpful.

      Reply

Leave a Comment