Languages
[Edit]
EN

Bash - detect key pressed

9 points
Created by:
Amir-Hashempur
547

In this short article, we want to show how to handle pressed key without waiting to rerun key / enter key confirmation under Bash.

Quick solution:

read -r -s -n 1 input

echo "$input"

Where:

  • -r disables waiting to type new line character to end read command (Return / Enter key is not required),
  • -s does not display typed characters,
  • -n 1 expects to type one character.

Alternatively you can use short version too: read -rsn1 input

 

Practical example

In this section, we want to show how to create a simple menu that doesn't require to pres Return / Enter key after the option is typed.

example menu.sh file:

#!/bin/bash

echo '1. Message'
echo '2. User'
echo '3. Exit'
echo
echo 'Select one option [1-3]'
echo

while true;
do
	read -r -s -n 1 input

	case "$input" in
		"1")
			echo "Selected 1 [1. Message]"
			;;
		"2")
			echo "Selected 2 [2. User]"
			;;
		"3")
			echo "Selected 3 [3. Exit]"
			exit 0
			;;
	esac
done

Alternative titles

  1. Bash - read key without waiting to enter
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join