How to get current gnome keyboard layout from terminal?

Solution 1:

According to a similar question on Stackoverflow, the following should do the trick:

setxkbmap -print | grep xkb_symbols | awk '{print $4}' | awk -F"+" '{print $2}'

I did could not verify it, as I currently have no *nix machine with X available (I'm not home)...

Solution 2:

For Ubuntu 17.10 or later

In Ubuntu 17.10, with GNOME, the current gsettings value is not changed when you switch input source. Instead there is a mru-sources key which lists the most recently used input sources.

$ gsettings get org.gnome.desktop.input-sources mru-sources
[('xkb', 'se'), ('xkb', 'us')]

The first source in that list is the current one, so a oneliner to get the current layout may look like this:

gsettings get org.gnome.desktop.input-sources mru-sources | sed -r "s/\S*\s'([^']+).*/\1/"

Please note that this answer does not apply if you use Unity on an Ubuntu 17.10 system. With Unity it keeps working as previously.

Solution 3:

For Ubuntu 13.04 and lower

You can use xkblayout-state tool. See README.md file for description, compilation, installation and usage.

The following command will do exactly what you want:

xkblayout-state print "%s"

For Ubuntu 13.10 and higher

Ubuntu 13.10 came with some good improvements in this sense, and you can use the following simple bash function:

get_current_xkblayout () {
      current_input_nr=$(gsettings get org.gnome.desktop.input-sources current | \
          awk '{ print $NF }')
      shift=$(( 2 * ( $current_input_nr + 1 )))
      gsettings get org.gnome.desktop.input-sources sources | tr -d "\',[]()" | \
          awk -v cur="$shift" '{ print $cur }'
}

The following commands also works in 13.10:

setxkbmap -query | awk -F"(,|[ ]+)" '/layout:/ { print $2 }'

or:

setxkbmap -print | awk -F"+" '/xkb_symbols/ {print $2}'

Solution 4:

Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.

setxkbmap -query

This is what you should see

enter image description here

Solution 5:

Using the terminal, I've run a test changing between 'pt' and 'us', and after every change, I've collected the keyboard layout being used with success:

Get the active keyboard layout

setxkbmap -print | grep xkb_symbols | awk -F"+" '{print $2}'
  • Print the configuration: setxkbmap -print
  • Collect the line that matters: grep xkb_symbols
  • gets the string after the first "+" sign: awk -F"+" '{print $2}'

The output having 'us' layout active is: us


Swith between layouts

sudo setxkbmap -option grp:alt_shift_toggle pt

Pass where it reads 'pt', the language code to switch to.

enter image description here

Note: I'm using Gnome on Ubuntu 12.04 (Precise Pangolin)