It’s been more than a year and a half now since I moved from Zsh to Fish, and I am still amazed by how smooth and simple it made my everyday workflow.

One little trick I’ve been taking with me from my Bash days is aliasing sudo to _. There are a lot of commands I need to run via sudo, and typing one character instead of four makes it obviously quicker. But what if I already started to write a command which needs proper privileges and forgotten about that precious sudo?

Lukas Stabe fixed it for me, years ago. First, let’s add his prepend_command to ~/.config/fish/functions/prepend_command.fish:

function prepend_command
    set -l prepend $argv[1]
    if test -z "$prepend"
        echo "prepend_command needs one argument."
        return 1
    end

    set -l cmd (commandline)
    if test -z "$cmd"
        commandline -r $history[1]
    end

    set -l old_cursor (commandline -C)
    commandline -C 0
    commandline -i "$prepend "
    commandline -C (math $old_cursor + (echo $prepend | wc -c))
end

Then, it’s only a matter of adding a key binding to ~/.config/fish/functions/fish_user_key_bindings.fish:

function fish_user_key_bindings
    fish_default_key_bindings

    # Prepend sudo with C-s
    bind \cs 'prepend_command sudo'
end

Now hitting Ctrl-s anywhere in the command I am typing immediately adds sudo at the beginning of the line.

prepend_command comes with the benefit of mimicking the sudo plugin of Oh My Zsh. Fish doesn’t support history expansion, but sometimes I just press Enter before remembering to hit Ctrl-s , and that’s where I’d love some history expansion. I can hit Ctrl-s right after the malevolent Enter , and have my previous command with sudo automatically prepended ready to go.

If you are accustomed to the Zsh key binding, you can have it in Fish too:

# Re-run previous command with sudo using ESC-ESC
bind \e\e 'prepend_command sudo'

Time savers, believe you me.