One particularly useful feature of both Bash and Zsh is their history mechanism, which makes it easy to recall commands you’ve typed in the past. Find out how to save time and avoid manual searches for complicated commands, by making full use of your shell’s command history.
What Is Shell History?
The shell history is a list of commands you have issued on the command line. Bash stores this history in a file called .bash_history in your home directory. In Zsh it’s called .zsh_history. You can use the history command to display the current contents of your history:
You can change the location of this file by setting the HISTFILE environment variable.
You can set the maximum number of history items with the HISTFILESIZE environment variable:
This sets the history file size to 1,000.
Shell history is useful when you want to repeat a command you typed earlier or change it without having to retype a line completely. The !! command will repeat the previously typed command. If you want to change something in the previously named command, enter ^old^new. Here, “old” is the part of the command line you want to replace and “new” is its replacement.
If you wanted to list the /bin directory after listing / with ls /, this is how you’d change the command:
This would be the same as if you’d typed ls /bin.
See also: How to Change the Default Shell on Linux With chsh
Command-Line Editing
Bash and Zsh both support command-line editing. This is a more flexible method to access your command history than history expansion. By default, the key commands are like those used by the Emacs editor. You can switch them to work more like Vim, if you want. Note, though, that the vim shortcuts are more awkward to use for command-line editing, even if Vim is great as a general text editor.
When you want to recall a command, just press the up arrow on your keyboard. You can press up to move through all your previous commands, while the down arrow lets you move to your more recent commands. You can also use Ctrl + P and Ctrl + N to scroll up and down through your history.
To search backward, press CTRL + R, then start typing to search the history until you see the command you want to edit. Press Ctrl + S to search forward.
To change a command line, you can move back and forth across the line using the right and left arrow keys. Alt + F will move forward by a word and Alt + B will move backward. To go to the beginning of a line, hit Ctrl + A. To go to the end, hit Ctrl + E. To delete a line completely, press Ctrl + K.
Now You Can Access Shell History
With a few simple methods, you can find your shell history and change commands without retyping the whole line. Both Bash and Zsh have command-line editing abilities that make it very easy. You have a choice of shells on Linux. Which one is best for you? Read on to find which Linux shell suits your working style.