the best way would be to not use a script, but to load a two-layer keyboard (eg: setxmodmap "us,se"
) and redefine the Ctrl-Esc to send ISO_Next_Group
Look at this answer on xkb for how to redefine some keys without need to edit main default files (thus, no need to be root).
In the local symbols file (eg: ~/.xkb/symbols/mysymbols
) put a small section as:
partial modifier_keys
xkb_symbols "ctrl_esc_toggle" {
key <ESC> {
type[Group1]="PC_CONTROL_LEVEL2",
symbols[Group1]= [ Escape, ISO_Next_Group ]
};
};
the PC_CONTROL_LEVEL2 tells that the sencond symbol for that key is got with Control (instead of Shift).
and in the local keymap file (eg: ~/.xkb/keymap/mykbd
; you can create it with setxkbmap "us,se" ; setxkbmap -print > ~/.xkb/keymap/mykbd
) change the xkb_symbols line to add "mysymbols(ctr_esc_toggle)"
so you will have someting like:
xkb_symbols { include "pc+us+se:2+inet(evdev)+terminate(ctrl_alt_bksp)+compose(rwin)+mysymbols(ctr_esc_toggle)" };
(note the "se:2", the ":2" tells to load the "se" symbols definitions as Group2; you can stack various groups).
you can now load it with: xkbcomp -I$HOME/.xkb ~/.xkb/keymap/mykbd $DISPLAY
then Ctrl-Esc will switch between "us" and "se" layouts.
NOTE however that you need to press Ctrl (and hold) before Esc; the other way it doesn't work (it would require defining a virtual modifier for Escape, and I don't know how to do it)