Shell – Checking if a specific key is pressed in shell script

shell-script

Is there a way I can check if a specific key is pressed in a shell script which is running in background. Consider I am running a shell script which has to play a play list of songs as soon as I press a key or combinations of 2 or 3 keys. This shell script will be added to crontab , so it won't be running in terminal. So is it possible to capture the keys pressed in this shell script?

Best Answer

Your requirements are not very much clear. But if I understand correctly, I would suggest you to first try out autokey-gtk. It is a python based application in which you can write your scripts in Python which will be executed whenever you press a pre-defined set of keys. See if this fits your need.

Then, if you want to do manually, there are essentially two ways:

Solution#1 : Keylogger Approach

You can write a script which would keep on logging your keyboard keys and initiate an event whenever a certain combination is pressed. For logging keys, you could look at the code of pykeylogger.

Solution#2 : Keybinder Approach

First of all you need to bind your keys using some method. One of the methods is using keybinder. Or you could simply bind your keys using "Keyboard Shortcuts" in your settings. Now, whenever you press a certain set of keys, a script would run which will write some text into a certain XYZ file in you home folder.

In the background, your script which was started using crontab would be reading this XYZ file every 1 second. According to the content of the file, this script will initiate different actions.

Related Question