Linux Shell Shortcuts

Written by Bruno Fontes, 27 Jun 2019


I am pretty sure most people who uses Linux knows these, but they are quite handy and it is not the kind of thing I usually see online, so here it goes a small list of shortcuts to be used on your favorite terminal/shell.

Let's say you were copying a file from a virtual domain to another one, so you type:

$ cp /var/www/old-website.com/public_html/mail/index.php
  /var/www/new-website.com/public_html/mail/index.php

So you remember that, actually, you want to move the file, not just copy that. On that case, you want to repeat all the parameters but the main command. So you can achieve that with...


The !* shell expansion

$ mv !*

This !* will expand into all the parameters of the last command:

$ mv /var/www/old-website.com/public_html/mail/index.php
  /var/www/new-website.com/public_html/mail/index.php

mv: cannot move '/var/www/old-website.com/public_html/mail/index.php' to
'/var/www/new-website.com/public_html/mail/index.php': Permission denied

Oops, you do not have permission to that. Now you just want to repeat exactly the same command, but using sudo this time. You can make it really simple again, just using...

The !! shell expansion

$ sudo !!

This will expand into your last command, as follows:

$ sudo mv /var/www/old-website.com/public_html/mail/index.php
  /var/www/new-website.com/public_html/mail/index.php

Yes, you finally moved the file into the right place. But it is not over yet. You still need to edit this moved file. Should you type the entire path this time? No! You can reuse just a parameter of your last commando with...


The !$ expansion

$ sudo vim !$

The !$ operator expands to the last parameter of the last command. So it will become:

$ sudo vim /var/www/new-website.com/public_html/mail/index.php


The !:<number> expansion

Another option is to pick the parameter by it's number. To achieve that, you can use the !:<number>, that will expand into the specified parameter, starting the numbering at 0.

  0    1  2                                                   
$ sudo mv /var/www/old-website.com/public_html/mail/index.php   
  3
  /var/www/new-website.com/public_html/mail/index.php

So we could have used !:3 instead of the !$ on the last command with the same result.

TL;DR and more...

There are much more shortcut, expansions etc, but here are a few that I like to use:

  • Ctrl+A - Go to start of command line
  • Ctrl+E - Go to end of command line
  • Ctrl+x, Ctrl+e - Edit the command line in your text editor- !! - Last command
  • !^ - First argument of last command
  • !$ - Last argument of last command
  • !* - All arguments of last command
  • !<command> - last command line of that command
  • !:<number> - argument of last command
  • !<command>:<number> - argument of the
  • ^foo^bar - Repeat last command replacing foo with bar
  • {1..10} - Expand to 1 2 3 4 5 6 7 8 9 10