Search code examples
bashshellkey-bindingsgnome-terminalopenconnect

Exit terminal after executing a command from .xbindkeysrc


I'm trying to bind a command to a key using .xbindkeysrc, namely this command retrieves a password from keepassxc, and echoes it as stdin to an openconnect (for VPN connection) command, and finally closes the terminal. The following does all of this, and it works:

psswd=`keepassxc-cli show -sa password path/to/MYKEEPASS.kdbx MY_ENTRY` ; echo $psswd | sudo openconnect --background --protocol=gp https://my.url --user=MYUSERNAME --passwd-on-stdin ; exit

However, this wouldn't work as a command in .xbindkeysrc, it needs to be executed in a terminal, which can be done by putting the previous code between "$()" as follows (again, this works), BUT without the "; exit" final bit (it does not work with it), therefore the terminal is not closed after running the full command.

gnome-terminal -e "$(psswd=`keepassxc-cli show -sa password path/to/MYKEEPASS.kdbx MY_ENTRY` ; echo $psswd | sudo openconnect --background --protocol=gp https://my.url --user=MYUSERNAME --passwd-on-stdin)"

Q1: How can I tell the terminal to close after executing the full command?

In addition, this simpler syntax (within "") is understood by .xbindkeysrc:

"gnome-terminal -e "sudo openconnect --protocol=gp https://my.url --user=MYUSERNAME""

but simply adding "" to the full command is not enough for .xbindkeysrc to run it when I press the bound key; this leads to my 2nd question:

Q2: How can I integrate the full command in .xbindkeysrc?

Thanks a lot


EDIT: after using Grisha Levit's answer:

"gnome-terminal -- sh -c 'pass=$(keepassxc-cli show -a password my_keepass_DB my_ENTRY) && printf "%s\n" "$pass" | sudo openconnect --background --protocol=gp https://my.url --user=my_NAME --passwd-on-stdin'"

there is an problem with vpnc-script, shown in lines 2,5-7:

Lines 2,5-7 are showing an error

The bit without the gnome-terminal -- does work:

sh -c 'pass=$(keepassxc-cli show -a password my_keepass_DB my_ENTRY) && printf "%s\n" "$pass" | sudo openconnect --background --protocol=gp https://my.url --user=my_NAME --passwd-on-stdin'

but this wouldn't work in .xbindkeysrc


Solution

    • You should pass the command to run in gnome-terminal as positional parameters rather than using the -e option. (i.e. gnome-terminal -- cmd arg...)
    • You can't use shell syntax directly, it must go through e.g. sh -c.

    So the command could be like:

    gnome-terminal -- sh -c 'pass=$(keepassxc-cli show -a password DB ENTRY) && printf "%s\n" "$pass" | sudo openconnect --background --passwd-on-stdin …'
    

    If that works, it should exit the terminal after starting the openconnect command so no exit needed.


    There's nothing special about this being in .xbindkeysrc -- just wrap the command above in double quotes.