Delete last N lines from bash history

Just this one liner in command prompt will help.

for i in {1..N}; do history -d START_NUM; done

Where START_NUM is starting position of entry in history. N is the number of entries you may want to delete.

ex: for i in {1..50}; do history -d 1030; done


As of bash-5.0-alpha, the history command now takes a range for the delete (-d) option. See rastafile's answer.

For older versions, workaround below.


You can use history -d offset builtin to delete a specific line from the current shell's history, or history -c to clear the whole history.

It's not really practical if you want to remove a range of lines, since it only takes one offset as an argument, but you could wrap it in a function with a loop.

rmhist() {
    start=$1
    end=$2
    count=$(( end - start ))
    while [ $count -ge 0 ] ; do
        history -d $start
        ((count--))
    done
}

Call it with rmhist first_line_to_delete last_line_to_delete. (Line numbers according to the output of history.)

(Use history -w to force a write to the history file.)


The history bash built-in command also takes a range, now in 2020:

-d offset

Delete the history entry at position offset. If offset is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of -1 refers to the current history -d command.

-d start-end

Delete the history entries between positions start and end, inclusive. Positive and negative values for start and end are interpreted as described above.

Only the command itself does not tell with --help:

 Options:
   -c        clear the history list by deleting all of the entries
   -d offset delete the history entry at position OFFSET. Negative
             offsets count back from the end of the history list

   -a        append history lines from this session to the history file
   ...

E.g. history -d 2031-2034 deletes four lines at once. You could use $HISTCMD to delete from the newest N lines backwards.


You can also export with history -w tmpfile, then edit that file, clear with history -c and then read back with history -r tmpfile. No write to .bash_history.