how to use the history command in Linux
The Linux shell keeps a history of the commands you run, so you can search it for repeated commands you’ve run in the past. Once you understand Linux’s history command and how to use it, it can greatly improve your productivity, according to HowToGeek.
What is the history command used for in Linux?
The history command in Linux allows you to review and redo previous commands. The longer and more complex the command, the more difficult it is to remember and enter without mistakes.
The history command fixes these problems. There are much better ways to use the history command than just pressing the up arrow repeatedly.
At its simplest, you can use the history command by simply typing its name:
Then a list of previously used commands is written to the terminal window.
The commands are numbered, and the most recently used (with the largest numbers) are at the end of the list.
To see a specific number of commands, you can add a number to history on the command line. For example, to view the last 10 commands you used, type the following:
You can achieve the same result by executing history via the tail command. To do this, enter the following:
history | tail -n 10
If you want to reuse a command from the history list, enter an exclamation mark (!) and the command number without spaces between them.
For example, to repeat command number 37, you need to enter this command:
To repeat the last command, type two exclamation marks, again without spaces:
This can be useful if you issue a command and forget to use sudo. Type sudo, a single space, double exclamation points, and then press Enter.
In the following example, we entered a command that requires sudo. Instead of retyping the whole line, we can avoid a bunch of keystrokes and just type sudo !!, as shown below:
mv ./my_script.sh /usr/local/bin/
So, you can enter the corresponding number from the list to repeat the command, or use double exclamation points to repeat the last command used. But what if you want to repeat the fifth or eighth command?
You can use a single exclamation point, a hyphen (-), and the number of any previous command (again, no spaces) to repeat it.
To repeat the 13th previous command, you must enter the following:
Read also on ProIT: Linux Mint 21.3 Virginia is now available for download. What’s new?
Subscribe to ProIT in Telegramso you don’t miss a post!