Running previous commands in Linux

Most non linux people tend to be taunted by the Linux command line, it’s no beast nor is the user behind it a super geek just because you see him hammering away at the keyboard with lines after lines of commands. Chances are he is repeating commands or changing commands here and there to get some results. In Linux the first time takes time and practice to produce accurate results. This is what most sysadmins spend their time doing but once you get the hang of it, it became a walk in the park.

How often do you repeat commands while using the command line? I do this all the time but sometimes it’s good to learn some shortcuts now and then to reduce repetitive tasks and improve efficiency.

When you type a command in the command line, it’s saved into the .bash_history file within the home directory. The history file will hold the last 500 commands. To view them you can use “history” or “history | less” if the result is too long. The history file is also frequently use for user/security audits and RCA work.

You will that within the output below each line is numbered, these numbers will come in handy later in this tutorial.

If you want to execute the last command you typed in again you would normally have to scroll up with the arrow key but this can also be done with “!!“. See sample below.

You could also execute a command from the history file by referring to the corresponding line number by using “![##]“. See sample below.

Using a string in place of the line number is also possible. The syntax for this is “![string]“. See sample below. The string value is matched against entries in the .bash_history file and the first matching entry will be excuted. For example if the “history” command existed on line 10, 100 and 450, line 450 would be returned.

Hope you find this helpful. Drop me a comment if you have questions or comments.