How to create a keyboard shortcut for a terminal command

I often work with git and loved iTerm2 for the ability to set keyboard shortcuts for commands. For example, I set CTRL+ENTER to git status.

Is this possible with gnome-terminal or can you recommend another option to achieve this?


You can use bind -x to bind a command to a shortcut in Bash. For example, to bind git status command to Crtl+p shortcut you can use:

 bind -x '"\C-p":git status'

Put it into ~/.bashrc file to remember it. From man page:

-x keyseq:shell-command

Cause shell-command to be executed whenever keyseq is entered. When shell-command is executed, the shell sets the READLINE_LINE variable to the contents of the Readline line buffer and the READLINE_POINT variable to the current location of the insertion point. If the executed command changes the value of READLINE_LINE or READLINE_POINT, those new values will be reflected in the editing state.


1. Automatically open a new terminal window, showing the output of your command

Since you need to keep the terminal open after the command ran, putting:

gnome-terminal -e 'bash -c "git status; read line"'

under a shortcut key combination, will do the job. It will open a new gnome-terminal window and run the command inside it.

Add it to a shortcut

Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:

gnome-terminal -e 'bash -c "git status; read line"'

to Ctrl+Enter

Note

Although your suggested shortcut works, you might pick another key combination then Ctrl+Enter, since it at least clashes with the LibreOffice shortcut to jump to a new page.

Explanation

To have a new gnome-terminal window opened from command line, and run a command in it, you can use:

gnome-terminal -e 'bash -c <command>'

However, although the command will run successfully, the terminal window will close immediately before you can read the output.

The section:

read line

is then to keep the terminal open (until you hit Enter) after the command runs.

Other commands

This way, you can run any (complex) command in the terminal, without having it closed immediately:

$ gnome-terminal -e 'bash -c "wmctrl -d; read line"'

will output (if wmctrl is installed):

enter image description here

After pressing Enter the terminal will close.

2. Running a command in the currently active gnome-terminal window

Of course you could place a simple one-liner under a shortcut key (assuming you have xdotool installed):

xdotool type "<command>"

This would however type the command blindly, in any application, and typing the command is not the cleanest option.

The small script below therefore:

  • looks if the active window is a gnome-terminal window (by its pid)
  • if so, it pastes the command in the active gnome-terminal window, presses Return.
    If not, the script does nothing, So it won't paste into other applications.

Since the script takes the targeted command as an argument, you can put multiple commands under multiple shortcuts.

The script

#!/usr/bin/env python3
import subprocess
import sys
import time

app = "gnome-terminal"
s = (" ").join(sys.argv[1:])

def get(cmd):
    return subprocess.check_output(cmd).decode("utf-8").strip()

def front(app):
    try:
        # see if gnome-terminal is running at all (raising error if not)
        app = get(["pgrep", app]) 
    except subprocess.CalledProcessError:
        app = False
    if app:
        # if so, see if the active window belongs to gnome-terminal comparing pids)
        active = get(["xdotool", "getwindowpid", get(["xdotool", "getactivewindow"])])
        return True if app == active else False

if front(app):
    # copy command to clipboard
    cm1 = ["/bin/bash", "-c", 'printf "'+s+'" | xclip -selection clipboard']
    # paste in terminal window
    cm2 = ["xdotool", "key", "Control_L+Shift_L+v"]
    # press return
    cm3 = ["xdotool", "key", "Return"]
    for cm in [cm1, cm2, cm3]:
        subprocess.call(cm)

How to use

  1. The script needs xdotool

    sudo apt-get install xdotool

  2. Create a dirctory ~/bin if it doesn't exist yet, either log out out/in or run source ~/.profile

  3. Copy the script above into an empty file, save it as gterm_keys (no extension) in ~/bin, an make it executable

Now You can run any command, from a shortcut key, in the frontmost gnome-terminal window by adding the command:

gterm_keys <command>

to a shortcut key, as described in [1]


In case zsh is used instead of bash, the following line in ~/.zshrc binds git status to ALT+ENTER.

bindkey -s '^[^M' 'git status\n'

To get ALT+ENTER in Bash, I use this line:

bind -x '"\e\C-m":git status'