Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script respond to keypress

I have a shell script that essentially says something like

while true; do
    read -r input
    if ["$input" = "a"]; then 
        echo "hello world"           
    fi
done

That is all well, and good, but I just realized having to hit ENTER presents a serious problem in this situation. What I need is for the script to respond when a key is pressed, without having to hit enter.

Is there a way to achieve this functionality within a shell script?

like image 554
j0h Avatar asked Jun 03 '14 13:06

j0h


2 Answers

read -rsn1

Expect only one letter (and don't wait for submitting) and be silent (don't write that letter back).

like image 67
pacholik Avatar answered Oct 22 '22 06:10

pacholik


so the final working snippet is the following:

#!/bin/bash

while true; do
read -rsn1 input
if [ "$input" = "a" ]; then
    echo "hello world"
fi
done
like image 19
Donald Derek Avatar answered Oct 22 '22 06:10

Donald Derek