Type Less By Using The History Feature In Bash Shell To Recall Previous Linux Commands

Bash shell has a robust history feature which makes it easy to keep a track of previous commands that can be run again whenever needed.

So if you spend a lot of time with Linux commands, this can save time by not entering same commands over and over.

Seeing previously used commands:

To get a list of previously used commands, from the shell/Terminal type:

history

displaying list of previous commands in bash shell

This will show all the commands as a list. The numbers make it easy to run them again without typing.

Run previous commands from history:

So to run the 5th command from the list above, specify that number :

!5

running a specific command from history list in bash shell

To execute the previous/last typed command, use:

!!

running the previous command from history

Also, if you first want to know what the last command really was rather than directly running it:

!!:p

displaying the previous command from history

The difference between !! and !!:p is that while the former directly runs the last command, the latter simply echoes it in Terminal and doesn’t run it.

difference between running and displaying previous command from bash history

You can also quickly list the last few commands, so to know which were the previous 3 commands, use :

history 3

seeing last 3 commands from history

Use shell scripts or aliases for long commands:

To avoid typing really long commands or multiple ones, just put them in a shell script and run that whenever needed. Another option is to set a short alias for them.

If it were the last command that is needed, redirect by typing :

echo “!!” >>  diskuseuptime.sh

redirecting long and multiple commands to a bash shell script

 

As with all shell scripts, first make it executable and then run it.

chmod +x diskuseuptime.sh

./diskuseuptime.sh

running the bash shell script that has a long command

The output will be the same as the commands entered before.

Clearing the history list:

Finally, to clear the history list, use the -c option :

history -c

clearing history list in bash shell

 

Overall, the history feature of Bash shell is a powerful option which can be a timesaver when frequently working with Linux command line.

All done.

 

 

Leave a Comment