Custom key to toggle keyboard layout

I want to set the key to toggle the language of my keyboard to "`" but I don't have this option at "Keyboard Layout" in Unity, in Ubuntu 12.04. I have already seen this answer but it doesn't help me. Can you please direct me as to how to use setxkbmap? (if that's the way to go). Thanks!


Here is an easy way to do it, but you are limited to what shortcuts you can use. Open "System Settings" -> "Keyboard". Click "Layout Settings", near the bottom. Click the + button to add any languages you need. Then click "Options..." There you can set the key combos you need, by selecting "Key(s) to change layout". If you want, you can also choose to use a keyboard LED to show when you are using your alternative layout (such as scroll lock) under "Use keyboard LED to show alternative layout".

Here is the slightly more involved way, but will give you more flexibility for the key combination. First, copy and paste this script I wrote and name it something like kb_toggle.sh. Make sure to edit LANG1 and LANG2 to be the keyboard layout codes you need.

#!/bin/bash

LANG1="us"
LANG2="de"
CURRENT_LANG=$(setxkbmap -query | tail -n 1 | cut -f6 -d ' ')
if [ "$CURRENT_LANG" = $LANG1 ]; then
    setxkbmap $LANG2
else
    setxkbmap $LANG1
fi

make the file by right-clicking on it -> "Properties" -> "Permissions" tab, then select "Allow executing file as program.

Now, open "System Settings" -> "Keyboard" -> "Shortcuts" tab and select "Custom Shortcuts". Click the + button on the bottom and name the shortcut "Keyboard Toggle" or whatever you want, really. Then give the full path to the script you made earlier in the command box. Hit Apply. Click where it says "Disabled" then you can set the shortcut to whatever you want by clicking your key combination!

One more thing. I don't think it will let you set it to a single key, like "", you may have to do SHIFT+ or something like that.


First: Thank you so much Reverendj1 for your script -- you rock! I've been struggling to find an answer as to why the "key(s) to change layout" selections are being totally ignored. As Dimitris said, it's not an answer, but it's a good work around.

Important: I did have to change one things on your script.
-- In 12.04 my final line of the setxkbmap -query output prints "options: grp:...". So, I used a pipe to grep "layout" instead of the "tail -n1" command. So the script looks as such:

#!/bin/bash
LANG1="us"
LANG2="de"
# CURRENT_LANG=$(setxkbmap -query | tail -n 1 | cut -f6 -d ' ') # OLD LINE
CURRENT_LANG=$(setxkbmap -query | | grep "layout" | cut -f6 -d ' ')
if [ "$CURRENT_LANG" = $LANG1 ]; then
    setxkbmap $LANG2
else
    setxkbmap $LANG1
fi

NB: If someone changes the number of spaces in the line "layout: us" then the -f6 option will fail to return "us". That will likely have to be fixed in the future.

Again, thank you so much for this fix. I can work much more efficiently now. ** Sorry, this was overly wordy