The more you work with the command line, the more often you need to repeat the commands you entered earlier. The easiest way to view the command history is to press the "up/down" keys. Each time you press the "up" arrow, the previously executed command will appear in the input field, if you press "down", the next command will appear.
The bash command history is stored in a special file called .bash_history
, which lies in the user's home directory. Every time the user enters a command, it goes into that file. It is no different from the other files: you can open it, view it, and even edit it. The HISTFILESIZE
environment variable is responsible for how many commands are stored in the history. If set, the number specified in it will be taken, otherwise, the history won't be cut off and the .bash_history
file will grow "infinitely".
tail .bash_history
rm -r one/
env
HOME=/tmp cd
pwd
cd
echo $HOME
export HOME=/tmp
id
exit
id
You can also view the history in a simpler way, just run the history
command.
history
1 docker ps
2 free -m
3 docker ps
4 docker exec -it 8678a6520641 bash
5 ls
6 exit
7 docker ps
8 docker exec -it 1209b6e5ce6b bash
...
This command will display the contents of the .bash_history
file, adding a number on the left. If you type history 5
, only the last 5 commands entered are displayed. By using the command number in the history
output, you can restart without having to type or copy the command from the history.
# This command had the second number in the listing above
!2
free -m
total used free shared buff/cache available
Mem: 1998 1532 75 21 390 227
Swap: 0 0 0
You can always grep the history if you need to:
history | grep export
174 export HOME=/tmp
183 history | grep export
Last, and most interesting, is the reverse-i-search (reverse interactive search). If you press Ctrl + r, a special history search will start. It waits for characters to be entered and immediately displays the closest command in which those characters occur. If you are not satisfied with the match, pressing Ctrl + r again will select the next match from the history.
The screenshot above is an advanced version of this search, working through the fzf utility.
Do it yourself
- Analyze the history on your local computer
- Experiment with reverse search