2

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?

PS- Transferred from https://stackoverflow.com/questions/61076286/key-binding-to-go-up-by-one-directory-in-bash

2

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-u":"cd .."' will bind a shell command (cd ..) to the keys (Ctrl+u) in emacs mode (the default mode).

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.

| improve this answer | |
  • The cd works, when this is bound to a free key binding. However, as the prompt is not refreshed, that's not really usable... – user3341592 Apr 8 at 13:59
  • I prefer this intermediate solution, which is not a hack: bind '"\e\C-u": "cd ..\n"' – user3341592 Apr 9 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.