Sometimes when working the cli you need to quickly run the last command, and either:
1. change something or 2. remove something
Using ^ (caret) substitution makes that easy, it runs the previous command substituting or removing what you specify by the carets (^^) here are couple of real *examples that I use frequently (and I’m sure you can think of quite a few more):
1. Change something.
Since I work on the cli a lot, and jump from host to host to get information, do stuff, get files, etc. I myself will sometimes jump to the wrong host, and as long as they are part of the same domain you can easily rerun the ssh command without having to type it all out again, e.g.:
shell#> ssh host1.mydomain.com now if host2 lives on same domain you can CTRL+C then shell#> ^host1^host2 and the shell will run ssh host2.mydomain.com.
2. Remove something.
Sometimes I want to remove an [option|name|file|pipe|blah] from the previous command:
Test to see if all dependencies for package are met:
shell#> rpm -ivh --test really-long-named-rpm.with.version.number.rpm
I don’t necessarily want to hit the up arrow (or k if you’re leet enough to use vi mode in cli (set -o vi)), backspace (no I’m not going to cover all the vi commands), remove –test and re-run the command. Here’s where ^ substitution comes into play, if I run:
It will happily re-run the previous command sans the –test option (you have to be specific, if you just did ^test^ it would leave the — (double dash) and might cause havoc, depending on command). So the substitution works from left to right, and only on the first occurrence. It works like this ^thing_to_replace^replacement. So in the above example we are substituting nothing for –test, essentially removing it. Obviously the one major caveat is that it only works on the previous command in the history.
Share and enjoy.
*Yes these examples may be lame, but they give you an idea.