Tuesday, 22 January 2013

Using Bash(shell) history effectively

Using Bash(shell) history effectively

The majority of these tricks utilize the ‘history’ command in some way, so let’s cover that one first. Just type:

history

To execute a specific command from your history, you can just type an exclamation point followed by the number of the command as listed by history. Here, I’ll re-execute command number 510.

!510
By the way, an exclamation point is referred to as a “bang.”

You can also refer to a command by how long ago it was run. Next, let’s execute whatever we typed three commands ago.

!-3

Quick Substitutions

Let’s say you want to rerun your previous command. Just type two exclamation points. This is perfect for when you run a command that needs super-user privileges and you forgot to do that. Just give it the old “sudo bang bang” treatment:

sudo !!

Let’s say you want to run a command with the last argument you used. Typing it out is too tedious. Just use a “bang dollar” to substitute your last argument automatically.

cd !$


What if you ran a command with two arguments and you want to run the first one? “Bang caret” This works well when you make a backup of a config file and then want to edit it.

nano !^


Next, let’s search for a specific command from your history. Ctrl+R will search backwards for whatever you type. It will autocomplete as you type, and you can scroll back up through the history if you hit Ctrl+R again to find the specific instance you’re looking for.



If you know the last command you ran with a specific keyword, you can skip the search process and pare down your key presses by at least one.

!keyword


Now, for the power substitution: you can substitute an argument for your last specific command using something similar to the previous method. Just add a colon and the number of the argument.

ls !ln:2

Here, I substituted the second argument from my last ‘ln’ command.



As you can see, I used a Ctrl+R lookup to help illustrate where that argument came from.

Once you’ve found the command you have several options:

  1. Run it verbatim – just press Enter
  2. Edit it before running – you can use arrow keys or different key bindings to navigate to the point you want to edit
  3. Cycle through other commands that match the letters you’ve typed – press Ctrl-R successively
  4. Quit the search and back to the command line empty-handed – press Ctrl-G

No comments:

Post a Comment