Using the history command
The command line is a great tool but it can be hard to remember commands even if we have used them before. The good news is that we don’t need to!
Shells like Bash and Zsh can store all commands that were previously executed and list them later with the history
command. Just make sure that the feature is enabled and configured in your shell of choice.
When the history
command is executed it will print the last used commands:
> history
9476 git diff backend
9477 git diff
9478 ./dev.sh restart
9481 ./dev.sh
9482 ./dev.sh kill
9483 code .
Notice that there are numbers printed for each history entry. We can use the numbers to refer to and re-execute a command from the history. Let’s say we want to run the git diff backend
again without having to retype it. All we need to do is to prefix the number with an exclamation mark:
> !9476
After pressing enter, the command line will be prepopulated with the chosen command. The command is not executed immediately and it is possible to modify it before it is run again.
To access the full power of the command history it is common to combine the history command with a search utility like grep
. In that case we can filter out the output to see only commands that we are interested in:
> history | grep diff
9469 git diff web-frontend/modules/database/components/table/Table.vue
9476 git diff backend
9477 git diff
Using the pipe operator (|) we let a program called grep
take the history output and filter the results to only those that contain the word “diff”. So the only thing we need to remember is the name of the program or some of its arguments.
And that’s how the history command can be used in a simple and practical way.
Until next time,
Petr