Skip to content

Controlling Your Keyboard with a Simple Bash Script

Published: at 02:16 PM

The Problem: Manually Controlling the Keyboard

Have you ever found yourself in a situation where you needed to quickly enable or disable your keyboard on Linux? Maybe you’re using an external keyboard and want to prevent accidental inputs from your laptop’s built-in keyboard. Or perhaps you need to temporarily disable your keyboard for some reason. Doing this manually can be a bit of a hassle.

The Solution: A Simple Bash Script

To solve this problem, I created a simple Bash script that allows you to enable or disable your keyboard with a single command. Here’s how it works:

#!/bin/bash
 
# Check if the user provided the correct number of arguments
if [ $# -ne 1 ]; then
    echo "Usage: ./keyboard.sh [enable|disable]"
    exit 1
fi
 
# Get the command-line argument (should be either 'enable' or 'disable')
action=$1
 
# Get the ID of your keyboard using xinput list
keyboard_id=$(xinput list | grep "AT Translated Set 2 keyboard" | grep -o "id=[0-9]*" | awk -F "=" '{print $2}')
 
# Check if the keyboard ID is valid
if [ -z "$keyboard_id" ]; then
    echo "Keyboard not found."
    exit 1
fi
 
# Check if the action is valid
if [ "$action" = "enable" ]; then
    xinput --set-prop "$keyboard_id" "Device Enabled" 1
    echo "Keyboard enabled."
elif [ "$action" = "disable" ]; then
    xinput --set-prop "$keyboard_id" "Device Enabled" 0
    echo "Keyboard disabled."
else
    echo "Invalid action. Please use 'enable' or 'disable'."
    exit 1
fi

The script takes one argument: either ‘enable’ or ‘disable’. It then uses xinput to find the ID of your keyboard (you’ll need to replace “AT Translated Set 2 keyboard” with the name of your keyboard). If the keyboard is found, the script will either enable or disable it based on the provided argument.

Using the Script

To use the script, simply save it to a file (e.g., keyboard.sh), make it executable with chmod +x keyboard.sh, and then run it with either ./keyboard.sh enable or ./keyboard.sh disable.