knowledge/bash-zsh_TerminalShorcuts.md

3.8 KiB

Shortcuts

For Ubuntu's default keybinding settings (i.e Emacs keybindings)

Insert previous arguments

  • Alt+.: insert last argument from last command.
  • Alt+number+.: insert #nth last argument from last command.
  • Alt+- , number , Alt+., zsh: Alt+-+#+.: insert #nth first argument from last command.

In Linux you can repeat commands to go back in history

Example:

Last command is:

mv foo bar
  • Alt+0+.: insert first argument of last command = mv
  • Alt+2+.: insert last 2nd argument of last command = foo
  • up , Ctrl+w: last command without the last word = mv foo

Cut/Paste commands

(relative to cursor's position)

  • Ctrl+w: cuts last word
  • Alt+d: cuts next word
  • Ctrl+k: cuts everything after
  • Ctrl+u, zsh: Alt+w: cuts everything before
  • zsh: Ctrl+u: cuts the entire command (In bash you can combine Ctrl+u , Ctrl+k)
  • Ctrl+y: paste characters previously cut with any Cut command. In bash you can chain cut commands, and Ctrl+y will paste them all.

Move cursor

  • Ctrl+left: move to last word
  • Ctrl+right: move to next word
  • home or Ctrl+a: move to start of command
  • end or Ctrl+e: move to end of command

Other

  • Ctrl+_: undo last edit (very useful when exceeding Ctrl+w)

To see all shortcuts available

  • bash: bind -lp
  • zsh: bindkey -L

Custom shortcuts

Iterate through arguments

only works in zsh, and probably only Linux

Description

Insert any argument of a previous command by iterating one by one until selection

Setup Instructions

run this:

autoload -Uz copy-earlier-word
zle -N copy-earlier-word
bindkey "^[:" copy-earlier-word

(to make this permanent, add it to your ~/.zshrc and restart shell)

Now use Alt+. to go as back as you want, then use Alt+: to iterate through the arguments

Example:

Last command is

echo 1 2 3 4 5
  • Alt+.: 5
  • Alt+.+:: 4
  • Alt+.+:+:: 3
  • Alt+.+:+:+:: 2
  • Alt+.+:+:+:+:: 1
  • Alt+.+:+:+:+:+:: echo

source: https://stackoverflow.com/a/34861762/3163120

Other examples

Common usecases

Let's consider the last command to be:

mv foo bar

up , Ctrl+w: last command without the last word = mv foo

Alt+0+.: first argument of last command = mv

Limitations

"words" only includes a-zA-Z characters, so any symbol character will stop word-shortcuts.

So if last argument was a url and you want to erase it with Ctrl+w it will be a pain.

E.g: curl -I --header "Connection: Keep-Alive" https://stackoverflow.com/questions/38176514/re-run-previous-command-with-different-arguments

To erase that url using Ctrl+w, you'd have to repeat it 12 times.


It would be great to have similar shortcuts that only stops at the space character