Command History

Command History

One of the useful features of the shell is its command history. This allows you to recall and execute previously entered commands easily.


Viewing Command History

You can view your command history using the history command:

$ history 

This will display a numbered list of your previously entered commands. The number next to each command is its history number.


Executing Commands from History

To execute a command from your command history, use its history number with the ! command:

$ !<history_number> 

For example, to execute the command with history number 10, you would enter:

$ !10 

You can also execute the most recent command by using !!:

$ !! 

This is useful for re-running a command quickly without having to type it out again.


Searching Command History

You can search your command history for a specific command using the history | grep command. For example, to search for the ls command in your command history:

$ history | grep ls 

This will display a list of all the commands containing the string ls in your command history.


Customizing Command History

You can customize the behavior of the command history by modifying the HISTSIZE and HISTFILESIZE environment variables.

HISTSIZE controls the number of commands that are stored in your command history in memory. For example, to set your command history size to 1000 commands:

$ export HISTSIZE=1000 

HISTFILESIZE controls the maximum number of commands that are saved to your command history file. For example, to set your command history file size to 5000 commands:

$ export HISTFILESIZE=5000 

By default, the command history is stored in the file ~/.bash_history. You can change this by modifying the HISTFILE environment variable:

$ export HISTFILE=<path/to/history/file> 


Conclusion

The command history is a powerful tool for increasing productivity on the command line. By customizing its behavior and using its features, you can save time and avoid repetitive typing.

Complete and Continue