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.

Key Takeaways

  • Learning about the bash command and its options.
  • Knowing different instances where to wait for user input.

Free Downloads

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.

Example 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.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a timeout.sh file in the build-in nano editor:

nano timeout.sh

EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • timeout.sh: Name of the file.

Creating timeoout.sh file in nano❸ Copy the following script and paste it in nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

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

The script starts with #!/bin/bash which specifies the Bash interpreter. 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.

❹ Use the following command to make the file executable:

chmod u+x timeout.sh

EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • timeout.sh: Name of the script.

Changing user permission for "bash wait for input"❺ Run the script by the following command:

./timeout.sh

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.

Example 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 nano editor.

You can follow the steps of Example 01 to know about creating and saving shell scripts.

Scripts (anykey.sh) >

#!/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.

Finally, run the file using the following command:

./anykey.sh.

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.

Example 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 in the nano editor.

You can follow the steps of Example 01 to know about creating and saving shell scripts.

Scripts (specifickey.sh) >

#!/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 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”

Finally, run the file using the following command to see the output.

./specifickey.sh

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.

Example 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. Copy the below script and paste it into the nano editor. Later, save the file as key_with_timeout.sh.

You can follow the steps of Example 01 to know about creating and saving shell scripts.

Scripts (key_with_timeout.sh) >

#!/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.

Finally, run the file using the command below:

key_with_timeout.sh

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. Open a file named ‘interactivemenu.sh’ & write the following script in the nano editor.

You can follow the steps of Example 01 to know about creating and saving shell scripts.

Scripts (interactivemenu.sh) >

#!/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
Then 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.

Finally, run the file using command below to visualize the interactive menu from the terminal.

./interactivemenu.sh

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 named ‘confirmation.sh’ & write the following script in the nano editor.

You can follow the steps of Example 01 to know about creating and saving shell scripts.

Scripts (confirmation.sh) >

#!/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.

Finally, run the file using the following command to visualize the output.

./confirmation.sh

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

Leave a Comment