7

I use more than one keyboard layout, and I would like to find a way to run a script when I switch between them.

Is this possible?

So far, I can assign a shortcut for a script like this:

#!/bin/bash

#switch between two layouts (English and Greek in this case)
current_layouts=$(gsettings get org.gnome.libgnomekbd.keyboard layouts)

if [ "$current_layouts" = "us" ]; then
    gsettings set org.gnome.libgnomekbd.keyboard layouts "['gr']"
else 
    gsettings set org.gnome.libgnomekbd.keyboard layouts "['us']"
fi

exec /path/to/another/script

But using this method, I can use only that shortcut to switch between layouts and the keyboard indicator will disappear from the status menu, what is unpleasantly.

4

dconf watch can be used as an event receiver, example (in Ubuntu 13.10/14.04):

dconf watch /org/gnome/desktop/input-sources/current | xargs -L 2 sh -c "echo kbd layout changed" &
  • Sadly, this no longer works with gnome 3.18 (I think it has to do with this so it affects earlier releases as well) – don_crissti Feb 19 '16 at 11:49
0

I would do it the other way around, run a script that changes the layout. That way you can do anything else you want with the same script. Unfortunately, it is quite hard to find out you current keyboard layout. I have found no approach that works for all methods of layout switching. For some reason, there is a difference if you switch with setxkbmap or via the GUI shortcuts.

So, my workaround is to always switch using setxkbmap. I have a script that calls setxkbmap and I have bound that script to a shortcut in my desktop environment so that I can switch easily. The example below is for Greek, and US layouts, you will have to modify it to fit your setup:

#!/usr/bin/env bash
key=`xmodmap -pke | grep -w "59" | awk '{print \$NF}'` 
## If this is the "us" layout, that will return "less"
if [ $key == "less" ]; then
    setxkbmap gr
    ## Add other things to be done here
else
    setxkbmap us
    ## Add other things to be done here
fi
  • Thanks for your effort, but this is not far from my script. The only difference: the keyboard indicator now appear, but with only one single layout. And yes... if there will be a way to determine the current keyboard layout (not all of them or first from them as I saw in other places) will be nice... – Radu Rădeanu Oct 9 '13 at 17:44
  • @RaduRădeanu I know, I've tried loads of methods but they are not consistent. The script in my answer simply disables the keyboard indicator on my DE so it's even worse. It's just the only way I know to run a script when changing layouts. I don't think it is possible if you use the GUI layout switcher. Do let me know if you find a better solution though! – terdon Oct 9 '13 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.