How to delete part of a path in an interactive shell?

Is there a shortcut in bash and zsh to delete one component of a path? For example, if I type ls ~/local/color/, and the cursor is at the end of line, is there a shortcut to delete the color/ at the end? Ideally I want solutions in both vi-mode and emacs-mode

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The most commonly used commands in the default bash emacs mode, for most commonly used keyboards:

Movement

  • Ctrlp, or Up: previous command
  • Ctrln, or Down: next command
  • Ctrlb, or Left: previous character
  • Ctrlf, or Right: next character
  • Altb: previous word
  • Altf: next word
  • Ctrla, or Home: begin of command
  • Ctrle, or End: end of command

Editing

  • BkSpc: delete previous character
  • Ctrld, or Del: delete current character
  • AltBkSpc: delete word to left
  • Altd: delete word to right
  • Ctrlu: delete to start of command
  • Ctrlk: delete to end of command
  • Ctrly: paste last cut

Miscellanea

  • Cltr/: undo
  • Cltrr: incremental backward history search

Method 2

There’s also unix-filename-rubout for Readline!

# in ~/.inputrc
# press ctrl-b to delete unix filename parts
# see: man bash | less -p 'unix-filename-rubout' and
#      http://www.calmar.ws/vim/vi-bash.html
set editing-mode vi
set keymap vi
"C-b": unix-filename-rubout

Method 3

By default bash (and I’m guessing zsh) will be in emacs-mode. You could try something like this:

Esc + b will put the cursor back one word.
Ctrl + k will delete until the end of the line.

Most modern shells (like bash) will implement advanced command line editing features. Those commands are either close to emacs editing (Ctrl +A for line beginning, Ctrl + E for line end, …).

If you’re familar with vi-like editors, you could try to allow vi-mode.

set -o vi

It gives your shell vi-like modes (command mode/insert mode), and you get access to the standard commands (d for delete, r for replace, …)

In Vi Mode, here’s how you would do what you described:

Esc (command mode); d; b.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x