A very powerful and cool command in Bash is history. Simply put, by default, Bash will store a history of all the commands you type. These are saved up to a certain threshold, and for our Ubuntu 18.04 installation this is 1,000 commands in memory and 2,000 commands on disk. Every time you do a clean exit/logout of your terminal, Bash will write the command history from memory to disk, taking both limits into account.
Before we dive (a little) deeper, let's take a look at our personal history for the reader user:
reader@ubuntu:~$ history
1013 date
1014 at 11:49 << wall "Hi"
1015 at 11:49 <<< wall "Hi"
1016 echo 'wall "Hi"' | at 11:49
<SNIPPED>
1998 array=("This" "is" "an" "array")
1999 echo ${array[0]}
2000 echo ${array[1]}
2001 echo ${array[2]}
2002 echo ${array[3]}
2003 echo ${array[4]}
2004 echo ${array[*]}
Even though our history is very interesting, it is not interesting enough to print it fully here. Often, if you use this in practice, it can easily become an overload of information as well. We suggest you use the history command in the following manners:
- history | less
- history | grep sed
If you pipe it to less, you'll end up with a nice pager that you can scroll through leisurely and use the search function in. When you exit it using q, you will be back at your uncluttered Terminal. If you're looking for a specific command (such as sed), you could also pipe the output of history through the grep command to make a course filter. If that's still too rough, consider adding | less behind the grep to make use of the pager once again.
The configuration for history is found in a few environment variables, which are often set in your ~/.bashrc file:
reader@ubuntu:~$ cat .bashrc
<SNIPPED>
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
<SNIPPED>
Here, you see the two defaults we had already announced (and which, if you want, can be edited!). For the others, man bash will inform you about the following:
- HISTCONTROL
- HISTFILE
- HISTTIMEFORMAT
Be sure to give those a quick read. Do not underestimate how convenient the history command can be; you will most certainly find yourself almost remembering how you used a command before, and if you remember enough you can use history to find out what you did so you can do it again.