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.
❶ 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
❸ 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
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
❺ Run the script by the following command:
./timeout.sh
Here, q is pressed within 5 seconds. So, the program terminates.
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.
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
Finally, run the file using the following command:
./anykey.sh.
The 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.
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
Finally, run the file using the following command to see the output.
./specifickey.sh
The 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.
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
Finally, run the file using the command below:
key_with_timeout.sh
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.
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
Finally, run the file using command below to visualize the interactive menu from the terminal.
./interactivemenu.sh
Here, user select option A, so the program terminates echoing a message “You selected Pizza. Enjoy your meal !”
This 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.
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
Finally, run the file using the following command to visualize the output.
./confirmation.sh
This 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.
This time user press neither ‘y’ nor ‘n’. Hence it shows a message of invalid input and waits for the user input again.
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
Related Articles
- How to Use Input Argument in Bash [With 4 Practical Examples]
- How to Use Bash Input Parameter? [5 Practical Cases]
- How to Read User Input in Bash [5 Practical Cases]
- How to Read CSV Files in Bash? [2 Methods]
<< Go Back to Bash Input | Bash I/O | Bash Scripting Tutorial