Ubuntu 18.04: how to change keyboard layout from a script?

In Ubuntu 16.04, the following thing worked:

/usr/bin/gsettings set org.gnome.desktop.input-sources current 0

But after upgrading to 18.04, it doesn't work anymore.

Answers 2

  • This method of switching keyboard layouts has been deprecated. The new, just slightly more cryptic way is this:

    gdbus call --session --dest org.gnome.Shell \
        --object-path /org/gnome/Shell \
        --method org.gnome.Shell.Eval \
        "imports.ui.status.keyboard.getInputSourceManager().inputSources[1].activate()"
    

    (credits: https://www.mail-archive.com/gnome-shell-list@gnome.org/msg08988.html)

    The number in inputSources[1] defines which layout you want. So, if you have two different layouts configured, it will be 0 or 1. You can get a list of the configured layouts by using this command:

    $ gsettings get org.gnome.desktop.input-sources sources
    [('xkb', 'us+intl-unicode'), ('xkb', 'us')]
    

  • The Sebastian's answer is great, I can confirm that it works much faster than the previous method that I used:

    gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'us')]"
    gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'us'), ('xkb', 'ru'), ('ibus', 'googlepinyin')]"
    

    To clearify his answer, the number in square brackets (inputSources[1]) is starting from 0, in my case 0 will be us, 1 ru and 2 pinyin in the following code:

    #!/bin/bash
    gdbus call --session --dest org.gnome.Shell \
        --object-path /org/gnome/Shell \
        --method org.gnome.Shell.Eval \
        "imports.ui.status.keyboard.getInputSourceManager().inputSources[1].activate()"
    

    You can store shell scripts for each language switch in your home directory, for example /home/user_name/.keyboard/langXX.sh. Remember to allow executing them.

    Then you need to add shortcuts in Settings/Devices/Keyboard/Custom Shortcuts: Screenshot


Related Questions