How to detect keystrokes?

5,042

you can read the keystrokes by the read command for this use the following bash script

#! /bin/bash
read -s -n 1 key # -s: do not echo input character. -n 1: read only 1 character (separate with space)
if [[ "$key" == "your key" ]];then
    #your script here
fi

you can experiment with the read command and some bash scripts

Share:
5,042

Related videos on Youtube

Anonymous Platypus
Author by

Anonymous Platypus

An information security nerd lives in the dark

Updated on September 18, 2022

Comments

  • Anonymous Platypus
    Anonymous Platypus 4 months

    I have a script running always at the background. Inside that script I have to write the codes to detect keystrokes, and once a particular keystroke is detected, the rest of the script must be executed. How can I do this?

    I have tried the showkey command but failed to add that to my script.

    • Anonymous Platypus
      Anonymous Platypus almost 8 years
      Please comment if I should supply any additional information.
    • stalet
      stalet almost 8 years
      So, is this a bash script that you want to run in the background and you want to trap some keystrokes while continuing to use bash shell commands ?
    • Fabby
      Fabby almost 8 years
      @AnonymousPlatypus: Any feed-back on the above comment?
    • Anonymous Platypus
      Anonymous Platypus almost 8 years
      Exactly its is! ;)
  • Anonymous Platypus
    Anonymous Platypus almost 8 years
    This might be useful. Will try this and get back to you :)
  • Ben Davis
    Ben Davis almost 3 years
    Note this only works for keys that emit one byte (letters, numbers, space, etc). Things like arrow keys, pgup, esc, etc. won't work with this.