First of all, if the command you're about to issue is sensitive, unsafe, or you just don't need it cluttering up your history, it is best/quickest to just prevent it from entering the history in the first place. Make sure that $HISTCONTROL
contains ignorespace
:
(bash)$ echo $HISTCONTROL ignoredups:ignorespace
Then proceed any command you don't want in your history with a space:
(bash)$ sensitive-cmd-with --password 82cf7dfe (bash)$ rm -r... # One-off recursive remove; mustn't be accidentally repeated!
If you accidentally put an unwanted command into history, providing that your bash session is still open, the command hasn't yet touched the disk. To delete the previous command in history, issue:
(bash)$ history -d $((HISTCMD-1))
Note the leading space; this command requires ignorespace
, otherwise it'll just delete itself!
If you want to delete the last few commands, find the last and first history number:
(bash)$ history 5 598 ok 599 sensitive 600 unsafe 601 doesn\'t-work 602 otherwise-unwanted
In this case 602 and 599. Then issue:
(bash)$ for i in ; do history -d $i; done
(Without ignorespace
, it would be 603..599.)
If you don't want any history from your current session to hit the disk, exit using:
(bash)$ kill -9 $$
The approach so far is to not even let sensitive history items be written to disk for extra security, because in theory data deleted from non-volatile media can still be recovered.
If, however, the command(s) you wish to remove are from a previous session, they will have already been appended to the $HISTFILE
on exit. Manipulating the history with the above commands will still only append the remaining new items to the $HISTFILE
, on exit. To overwrite the $HISTFILE
with the current session's view of the entire history, right now, issue:
(bash)$ history -w
Of course for history items already on disk, the alternative to editing the history with history -d
commands then issuing history -w
, is to edit the $HISTFILE
with a text editor.