Wednesday | 24 APR 2024
[ previous ]
[ next ]

Notes on Editing Commands - Bash

Title:
Date: 2022-11-17
Tags:  

A very simple little thing that I hope to get some use out of. You can trigger the editor if you set up the EDITOR environment variable in a command. This will make it easier to edit multiline commands and anything that might be complex.

Add this to your ~./bashrc

EDITOR=vim

This will set up the default editor.

Now you can use C-xC-e to edit a command. This is Ctrl x Ctrl e.

The default behavior is that once you exit the editor, it will execute the command. I'm not a fan so we can add snippet that will simply place the command ready to be executed.

This is also added to bashrc.

_edit_wo_executing() {
    local editor="${EDITOR:-nano}"
    tmpf="$(mktemp).sh"
    printf '%s\n' "$READLINE_LINE" > "$tmpf"
    $editor "$tmpf"
    READLINE_LINE="$(<"$tmpf")"
    READLINE_POINT="${#READLINE_LINE}"
    rm "$tmpf"
}

bind -x '"\C-x":_edit_wo_executing'

I also changed the binding to be Ctrl x here. I would like a one key option but it seems it needs to be followed by any keypress to actually open the editor. But this is fine for now.

Not sure if I'll actually use it as I use fish as my main shell and I haven't got it working there yet.