Bash wait for keypress

29/12/2020
`read` command is used to take user input in a bash script. We can take input in bash script by using various types of options with the read command. Sometimes we need to write the script in such a way that the script will run until a specific key is pressed or the particular script will execute based on the specific key or the program will wait for the specific amount of time until any key is pressed. How you can write bash script to wait for any particular key or any key to some tasks is shown in this tutorial by using different examples.

Example#1:

Create a bash file with the following script. When you will run the script, it will continue until the user presses any key. The script will wait for the user’s input in every 3 seconds and if the user doesn’t press any key then it will print the message, “waiting for the keypress“.

#!/bin/bash
echo "Press any key to continue"
while [ true ] ; do
read -t 3 -n 1
if [ $? = 0 ] ; then
exit ;
else
echo "waiting for the keypress"
fi
done

Run the script.

$ bash key1.sh

Output:

Example#2:

Create a bash file with the following script. An infinite while loop is used in this example that will terminate when the user will press ‘q’. If the user presses any key without ‘q’ then the value of the counter variable will be increased by 1 and print the value.

#!/bin/bash
echo "Press ‘q’ to exit"
count=0
while : ; do
read -n 1 k <&1
if [[ $k = q ]] ; then
printf "nQuitting from the programn"
break
else
((count=$count+1))
printf "nIterate for $count timesn"
echo "Press ‘q’ to exit"
fi
done

Run the script.

$ bash key2.sh

Output:

Example#3:

Create a bash file with the following script that will do different types of tasks based on the key pressed by the user. If the user presses ‘1’ then it will add two command line arguments and print. If the user presses ‘2’ then it will subtract two command line arguments and print. The script will run continuously until the user presses ‘3’.

#!/bin/bash
v1=$1
v2=$2
while :
do
echo "1. Addition"
echo "2. Subtraction"
echo "3. Quit"
echo -n "Type 1 or 2 or 3 :"
read -n 1 -t 15 a
printf "n"
case $a in
1* )     echo "$v1 + $v2 = $(($v1+$v2))";;
 
2* )     echo "$v1$v2 = $(($v1-$v2))";;
 
3* )     exit 0;;

 
* )     echo "Try again.";;
esac
done

Run the script with two numeric argument values.

$ bash key3.sh 35 15

Output:

Example#4:

Create a bash file with the following script. The script will terminate when the user will press ESC key. This script will print the keys pressed by the user until ESC key is pressed.

#!/bin/bash
userinput=""
echo "Press ESC key to quit"
# read a single character
while read -r -n1 key
do
# if input == ESC key
if [[ $key == $‘e’ ]];
then
break;
fi
# Add the key to the variable which is pressed by the user.
userinput+=$key
done
printf "nYou have typed : $userinputn"

Run the script.

$ bash key4.sh

Output:

Example#5:

Create a bash file with the following code that will wait for ENTER key to terminate the script. The script will take a server name as input and will try to ping the server in every 2 seconds. If ping command gets the response from the server then it will terminate the script by displaying the output otherwise it will wait for the user’s response or ENTER key by printing the message, “Trying to connect with…”.

#!/bin/bash
echo "Enter the server address that you want to ping"
read server
while ! ping -c 1 -n -W 2 $server
do
echo "Trying to connect with $server"
echo "Press [ENTER] to terminate"
read -s -N 1 -t 1 key
if [[ $key == $‘x0a’ ]];        # if input == ENTER key
then
exit 0
fi
done
printf "%sn" "$server is running"

Run the script.

$ bash key5.sh

Output:

Conclusion:

This tutorial shows how you can write the bash script in various ways that will wait for the user’s input to do any specific task or terminate the script. Hope, after practicing the above examples, you will be able to write the script in such way that can wait for any keypress and do the particular task based on the key pressed by the user.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Tổng hợp 15 lệnh OpenVZ commands thông dụng

1, Command to list the running VPSs in a node # vzlist Example: # vzlist CTID NPROC STATUS IP_ADDR...
20/09/2021

Bash brace expansion

Bash uses brace expansion to generate a sequence of strings from the terminal or by using any bash script. A sequence of...
29/12/2020

Bash Script User Input

Taking input from the user is a common task for any programming language. You can take input from a user in bash script...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

mua Proxy riêng ở đâu, và nó đem lại lợi ích gì cho người sử dụng
22/11/2022

Hướng dẫn sử dụng Proxy Helper Fakeip khi thuê proxy
21/11/2022

PROXY NUÔI TÀI KHOẢN FACEBOOK – KINH NGHIỆM FAKE IP – THUÊ PROXY GIÁ RẺ
14/11/2022

Mua Proxy Nuôi Zalo Giá Rẻ Tại Onet.com.vn
14/11/2022

BẢNG GIÁ MUA PROXY VIỆT NAM và PROXY US Onet.com.vn
14/11/2022