Lazy Shell Shortcuts

Because of the lonely way I learned shell programming (re-purposing and adapting code from others with extensive stack-overflow research), everything I know has to do with script writing. So, recently, while preparing for my first time teaching others about the shell, I had a chance to discuss command-line magic with a more experienced coder, Stephen Turner, and he told me about two basic shortcuts that I did not know.

1. Quickly Subsitute Strings to Adapt Previous Commands

What if I got ahold of a file containing a list of all the names of every student that ever attended Hogwarts (one per line) and I wrote a long command to discover how many students had “Neville” somewhere in their name?

$cat hogwarts.txt | grep "Neville"| wc -l

And now I want to run pretty much the same command, but with a small change — perhaps I want to use the Gryffindor specific list instead. Like this:

$cat gryffindor.txt | grep "Neville"| wc -l

For years, I have used the up arrow and then scrolled to the start of the command in order to change it. But, no longer.
Instead, I can use the ^ caret (on the 6 key) to substitute gryffindor for hogwarts in the previous command, like so:

cat gryffindor.txt | grep "Neville"| wc -l

And Boom, the shell prints out the new command and starts running it!

2. Use History as More Than Just a Record of Your Commands

Did you know that history will bring up a numbered list of your command history? Well, I did. I did not know that you can use those numbers to reissue commands. How cool is that? Answer: So cool. Here’s how it works. First call up your history:

1 ls
2 cd ~
3 plink --out ravenclaws --keep ravenclaw.txt --bfile hogwarts --freq
4 cowsay "Be Lazy!"
5 cat ravenclaw.log
6 head ravenclaw.freq

Take note of the number beside the command you wish to rerun, in this case, obviously, the cowsay command. Now, use an ! exclamation mark and that number to reissue that command:

cowsay "Be Lazy!"


Those of you that already knew such magic, I congratulate you. Any of you that didn’t, I hope these serve you well!