40

When accidentally pasting a file into the shell it puts a ton of ugly nonsense entries in the bash history. Is there a clean way to remove those entries? Obviously I could close the shell and edit the .bash_history file manually but maybe there's some kind of API available to modify the history of the current shell?

36

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.)

  • 1
    Since the OP asked for deleting the N last lines, this script should be modified by doing something like: tot_lines=$(history | wc -l) and then repeat history -d $(( tot_lines - $1 )). – PlasmaBinturong Jan 19 '18 at 9:13
  • 2
    Instead of $(history | wc -l), there is the variable $HISTCMD that can be used. – PlasmaBinturong Jan 19 '18 at 9:58
29

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

  • 3
    I wonder why this is not a built-in function already. 'history' is a very old tool. – Petr Gladkikh Aug 1 '16 at 9:23
  • serves the purpose very well, but this command can be seen in history :) – Rajeev Akotkar Nov 26 '18 at 4:12
  • askubuntu.com/a/978276/22866 has a nice way to delete the "delete from history command" from history :-) – HanSooloo Jul 4 at 6:46
0

The answer by user2982704 almost worked for me but not quite. I had to make a small variation like this.

Assuming my history is is at 1000 and I want to delete the last 50 entries

start=1000

for i in {1..50}; do count=$((start-i)); history -d $count; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.