Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a single command from history in bash

After some searching online I found that the following command should remove a single entry from the bash history:

$ history -d <number>

So let's say I would like to remove this single line from my history because I misspelled git :

10003 gti add . && git commit -m

When I do the following command:

$ history -d 10003

It still shows up in my history, even when I restart the terminal

So any idea how I can fix this because I use autocomplete and sometimes especially when using git it can get a bit messy.

like image 871
Timothy Kodes Avatar asked Dec 07 '25 08:12

Timothy Kodes


2 Answers

Command history in Bash is stored both in-memory, typically for the current shell session, and on disk, by default in ~/.bash_history. A default history configuration might append the in-memory session to the file on disk when the session is terminated, but there are a lot of knobs to tweak.

To permanently delete a command from history, after running history -d <number>, you can run history -w. This writes both the in-memory session and any edits to the older history back to the ~/.bash_history file.

You could also edit the ~/.bash_history file directly. As long as you don't run history -w in this case, the older commands will not be touched when the current Bash session exits.

A few references to history settings:

  • HISTFILE – the file where history is persisted (defaults to ~/.bash_history)
  • HISTFILESIZE – the number of commands stored in the history file (defaults to HISTSIZE)
  • HISTSIZE – the number of commands stored in the (in-memory) history list (defaults to 500)
  • cmdhist – shell option to save multi-line commands in a single history entry
  • histappend – shell option to control if the history list is appended to the history file, or if the history file is overwritten
  • lithist – shell option to store multi-line commands using linebreaks instead of semicolons

The -w option was recommended in this answer on the Unix & Linux Stack Exchange site.

like image 81
Benjamin W. Avatar answered Dec 08 '25 21:12

Benjamin W.


It's solved by deleting the command from ~/.bash_history

like image 36
Timothy Kodes Avatar answered Dec 08 '25 21:12

Timothy Kodes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!