linuxbashshellkey-bindings

Key binding to go up by one directory (in Bash)


In Zsh, I have a key binding to go up by one directory (very useful):

# C-M-u: up-directory
up-directory() {
    builtin cd .. && zle reset-prompt
}
zle -N up-directory
bindkey '\e\C-u' up-directory

It's very nice. So nice that I would like to get it as well in my Bash config.

How can we do that?


Solution

  • You can do that. It's not as elegant or straight forward as with zsh but it's doable in bash using bind.
    You can not only bind built in Readline functions (listed with bind -l) but other macros and shell functions too.

    bind -m emacs -x '"\C-i":"cd .."' will bind a shell command (cd ..) to the keys (Ctrl+i) in emacs mode (the default mode). (Ctrl+i is unbound by default, u isn't)

    Note that your prompt will probably not reflect the change.
    If you leave out -x the string will instead be typed out for you so "cd ..\n" achieves the same result.

    Edit: bind is how you bind keys and macros can accomplish what you want even though no built in thing exists.

    If you end your PS1 prompt with \033[K (erase to eol) and can use
    bind -m emacs '"\C-i":" cd ..&&echo -e \"\\033[2A\"\n"' to do what you want.
    This will first print cd .. then control chars to move the cursor up and run it (with \n). The end of your PS1 prevents it from showing. This is a hack but it shows that it's doable.