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

Viewed 574

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?

2 Answers

In case someone still need this:

This binds cd .. to F2. Keeps the currently typed command and throws an updated prompt.

bind '"\eOQ": "\C-a\C-kcd ..\C-m\C-y"'

How it works:

  • \eOQ is F2 on my terminal
  • C-a beginning-of-line
  • C-k kill-line
  • cd ..
  • C-m accept-line
  • C-y yank <- this restores the killed line

However the cd .. command appears in the screen. If it bothers you, use this instead:

bind -x '"\201":cd ..'
bind '"\eOQ": "\C-a\C-k\201\C-m\C-y"'

\201 is non existent key, an empty slot we can use.

Note1: It doesn't save the cursor position, after F2 the cursor lands on the end of the line, which is a little limitation.

Note2: The original was: bind '"\eOQ": " \C-a\C-k\201\C-m\C-y\C-b\C-d"' which adds an extra space, then removes it. I don't know why, maybe it was some workaround in the old ages when i wrote this, but it looks it does not needed now.

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.

Related