Bernd
Bernd

Reputation: 11493

Bash Scripting, Respond to Keypress

I built a tiny menu to use in a bash terminal with multiple options to select via number keys.

#!/bin/bash
PS3='Teleport to ... '
options=("→ option 1" "→ option 2" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "→ option 1")
            echo "option 1"
            break
            ;;
        "→ option 2")
            echo "option 2"
            break
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option
            break
            ;;
    esac
done

At the moment I still need to confirm the selection by pressing enter. Is it possible to make the script respond to the input of the first pressed key directly?

Upvotes: 0

Views: 552

Answers (2)

Zsolt Botykai
Zsolt Botykai

Reputation: 51593

Yep, with bash (and not sh!) you can use something like:

_KEY=
read -d '' -sn1 _KEY

Upvotes: 1

choroba
choroba

Reputation: 241808

read -n 1 reads one character. You cannot use select with it, though, so you have to write the while loop yourself.

Upvotes: 2

Related Questions