Check Lock Keys state from command-line

7,976

Solution 1

simply run:

xset q

From man xset:

q       The q option gives you information on the current settings.

In the top section of the output, you will find your information, looking like:

Keyboard Control:
  auto repeat:  on    key click percent:  0    LED mask:  00000003
  XKB indicators:
    00: Caps Lock:   on     01: Num Lock:    on     02: Scroll Lock: off
    03: Compose:     off    04: Kana:        off    05: Sleep:       off
    06: Suspend:     off    07: Mute:        off    08: Misc:        off
    09: Mail:        off    10: Charging:    off    11: Shift Lock:  off
    12: Group 2:     off    13: Mouse Keys:  off

You can use grep to get specific result as follows:

$ xset -q | grep Caps
    00: Caps Lock:   off    01: Num Lock:    on     02: Scroll Lock: off 

Solution 2

With xset you could use the following sed command:

xset -q | sed -n 's/^.*Caps Lock:\s*\(\S*\).*$/\1/p'

As an example, say you want to check if caps lock is enabled, and if so to disable it. For that you could do:

caps_lock_status=$(xset -q | sed -n 's/^.*Caps Lock:\s*\(\S*\).*$/\1/p')
if [ $caps_lock_status == "on" ]; then
  echo "Caps lock on, turning off"
  xdotool key Caps_Lock
else
  echo "Caps lock already off"
fi
Share:
7,976
Pandya
Author by

Pandya

Started using Linux and StackExchange since Ubuntu 12.04 LTS. Then Upgraded to 14.04 LTS. Now I am using Debian GNU/Linux on my Laptop and PureOS on old Desktop computer. I recommend visiting the Philosophy of GNU Project As I've replaced Ubuntu with Debian GNU/Linux, Now my question(s) are became off-topic on AskUbuntu. So, I continue to Unix & Linux. The second reason for my shifting to U & L is I found U & L more interesting than AU since AU is only Ubuntu specific whereas U & L is a broad concept and in my opinion U & L deserves generic questions. (I know why SE has AU & U & L both).

Updated on September 18, 2022

Comments

  • Pandya
    Pandya almost 2 years

    I want to check Lock keys (i.e Caps Lock, Num Lock, Scroll Lock etc.) state (On/Off) from command-line. How do I check state via terminal command?

  • Teodor
    Teodor over 3 years
    I want to use caps state as an if conditional. (Specifically, I want to bind caps to control, but I only want to do that when caps isn't press, that leaves me IN PERMANENT ALL CAPS, WHICH IS NOT WHAT I WANTED! (phew). Suggestions?