That's another excellent question! Sometimes you might want to clear your shell history for privacy, security, or just to tidy things up.
There are a few ways to clear your shell history:
-
Clear history for the current session and remove from history file (most common and thorough):
history -c history -whistory -c: This command clears the command history from the current session's memory. This means if you typehistoryright after this, it will show an empty list (or start from 1 again).history -w: This command writes the current in-memory history (which is now empty) to the history file (~/.bash_history). This effectively overwrites the history file with an empty set of commands.
-
Delete the history file directly (less graceful but effective):
rm ~/.bash_historyThis command directly deletes the history file. However, your current session's history in memory will still exist until you exit the terminal or use
history -c. If you delete the file and then exit, your current session's history will be written to a new.bash_historyfile. So, oftenhistory -cfollowed byrm ~/.bash_history(orhistory -wto clear the file) is more complete if you want no trace. -
Prevent commands from being saved in history temporarily:
If you prepend a command with a space, it typically won't be saved in your history (this depends on theHISTCONTROLshell variable, which is usually set to ignore space-prefixed commands by default).
Example:mysecretcommand --with-sensitive-data(Notice the space before
mysecretcommand)
Choose the method that best suits your needs. Using history -c followed by history -w is generally the safest and most complete way to clear the history both from memory and from the file for the current user.