Languages
[Edit]
EN

Bash - detect arrow key pressed

4 points
Created by:
Root-ssh
116210

In this short article, we would like to show how to detect any arrow key pressed in Bash.

Arrow keys pressed detection in Bash.
Arrow keys pressed detection in Bash.

Quick solution (input.sh file):

#!/bin/bash

while read -rsn1 input
do
    case "$input"
	in
		$'\x1B') # ESC ASCII code (https://dirask.com/posts/ASCII-Table-pJ3Y0j)
			read -rsn1 -t 0.1 input
			if [ "$input" = "[" ]
			then
				read -rsn1 -t 0.1 input
				case "$input"
				in
					A) echo '[Arrow Up]'   ;;
					B) echo '[Arrow Down]' ;;
					C) echo '[Arrow Righ]' ;;
					D) echo '[Arrow Left]' ;;
				esac
			fi
			read -rsn5 -t 0.1   # flushing stdin
			;;
		q) # q letter
			break
			;;
		*) # other letters
			echo "$input"
			;;
    esac
done

Example output (↑ → ↓ ←):

$ ./input.sh
[Arrow Up]
[Arrow Righ]
[Arrow Down]
[Arrow Left]

 

Reusable function

Using the below example you can reuse read_key() function in your code. The function returns arrow custom codes: [Arrow Up], [Arrow Down], [Arrow Righ], [Arrow Left] and letters.

#!/bin/bash

function read_key()
{
	if read -rsn1 input
	then
		if [ "$input" = $'\x1B' ] # ESC ASCII code (https://dirask.com/posts/ASCII-Table-pJ3Y0j)
		then
			read -rsn1 -t 0.1 input
			if [ "$input" = "[" ]
			then
				read -rsn1 -t 0.1 input
				case "$input"
				in
					A) echo '[Arrow Up]'   ;;
					B) echo '[Arrow Down]' ;;
					C) echo '[Arrow Righ]' ;;
					D) echo '[Arrow Left]' ;;
				esac
			fi
			read -rsn5 -t 0.1   # flushing stdin
		else
			echo "$input"
		fi
		return 0
	fi
	return 1
}


# Usage example:

while true
do
	input="$(read_key)"
	
	if [ "$?" -eq 0 ]
	then
		case "$input"
		in
			q) # q letter
				break
				;;
			*) # arrows + other letters
				echo "$input"
				;;
		esac
	fi
done

See also

  1. Bash - interactive menu example (arrow up and down selection) 
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