195

Commands follows

  511  clear
  512  history
  513  history -d 505
  514  history
  515  history -d 507 510 513
  516  history
  517  history -d 509
  518  history
  519  history -d 511
  520  history

I can delete single one by history -d 511, but how to delete last 10 commands and in between 10 commands history using single command in shell?

Can we write a bash script and execute for deletion of history?

Justin John
  • 9,223
  • 14
  • 70
  • 129
  • 25
    `vi $HISTFILE` and delete what you want. Use `head -n -10` if you have to automate it. – Anton Kovalenko Feb 07 '13 at 12:07
  • Is this question **off-topic**? or This is not wright place to ask this kind of question? If so, where should I ask this question, I mean where in stack exchange? – Justin John Feb 07 '13 at 12:14
  • @Barmar: I am using ssh. – Justin John Feb 07 '13 at 12:17
  • 1
    Shell commands work the same whether you're logged in locally or via ssh. – Barmar Feb 07 '13 at 12:19
  • 2
    Unix and Linux StackExchange (unix.stackexchange.com) is probably a better venue for this question. It's off-topic here because it doesn't relate strictly to programming. – Dan Moulding Feb 07 '13 at 12:32
  • @DanMoulding Can this question migrate to unix.stackexchange.com? If so, how? – Justin John Feb 07 '13 at 12:37
  • 5
    Programming a shell script is the ideal solution to this question, consequently it should be considered related to programming. Not to mention the fact that the OP actually asked specifically for a script. – SSH This Jan 22 '14 at 02:26
  • `history -d 1326` to delete just one item. Get the id from `history`. Incase you're like me, and googled how to remove the last line, and this is the first result. – Mint Apr 14 '21 at 23:00

21 Answers21

143

Have you tried editing the history file directly:

~/.bash_history
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
WheretheresaWill
  • 5,882
  • 7
  • 30
  • 43
  • 3
    @WherethereisaWill OP wanted a script, not a manual plug and chug. – Tyler Jandreau Feb 07 '13 at 12:11
  • 14
    will take effect after relaunching (closing and re-opening) the terminal – khaled_webdev Dec 11 '14 at 10:13
  • 9
    If you do this with vim you may find your deletion history in `~/.viminfo` so be sure to remove that too! – waltwood Jul 22 '15 at 22:39
  • 5
    sometimes it's kept in memory and any manual editing wont be persisted after next login.. – superhero Sep 15 '16 at 08:39
  • @ErikLandvall You have to close the terminal and open another terminal and edit the history file. – Fizer Khan Nov 29 '16 at 07:03
  • 4
    @FizerKhan that wont help the fact that it's kept in memory. It's the history file that is kept in memory sometimes, so even if you edit the file it wont take effect.. – superhero Nov 29 '16 at 09:47
  • @ErikLandvall Understood. You mean: Even If I close the terminal, there is no guarantee that history will be write to `.bash_history` file? – Fizer Khan Nov 29 '16 at 10:27
  • 7
    @FizerKhan I mean that changes made in `.bash_history` can be overwritten by what is kept in memory. I found this solution helpful: http://superuser.com/a/384383/253543 – superhero Nov 29 '16 at 10:42
  • and its ~/.zsh_history for zsh. don't forget to to relaunch terminal – Ivor Scott Jun 09 '19 at 02:53
127

My answer is based on previous answers, but with the addition of reversing the sequence so that history items are deleted from most recent to least recent.

Get your current history (adjust the number of lines you want to see):

history | tail -n 10

This gives me something like

1003  25-04-2016 17:54:52 echo "Command 1"
1004  25-04-2016 17:54:54 echo "Command 2"
1005  25-04-2016 17:54:57 echo "Command 3"
1006  25-04-2016 17:54:59 echo "Command 4"
1007  25-04-2016 17:55:01 echo "Command 5"
1008  25-04-2016 17:55:03 echo "Command 6"
1009  25-04-2016 17:55:07 echo "Command 7"
1010  25-04-2016 17:55:09 echo "Command 8"
1011  25-04-2016 17:55:11 echo "Command 9"
1012  25-04-2016 17:55:14 echo "Command 10"

Select the start and end positions for the items you want to delete. I'm going to delete entries 1006 to 1008.

for h in $(seq 1006 1008); do history -d 1006; done

This will generate history -d commands for 1006, then 1007 becomes 1006 and 1006 is deleted, then 1008 (became 1007) is now 1006 and gets deleted.

If I also wanted to delete the history delete command then it's a bit more complicated because you need to know the current max history entry.

You can get this with (there may be a better way):

history 1 | awk '{print $1}'

Putting it together you can use this to delete a range, and also delete the history delete command:

for h in $(seq 1006 1008); do history -d 1006; done; history -d $(history 1 | awk '{print $1}')

Wrap this all up in a function to add to your ~/.bashrc:

histdel(){
  for h in $(seq $1 $2); do
    history -d $1
  done
  history -d $(history 1 | awk '{print $1}')
  }

Example deleting command 4, 5 and 6 (1049-1051) and hiding the evidence:

[18:21:02 jonathag@gb-slo-svb-0221 ~]$ history 11
 1046  25-04-2016 18:20:47 echo "Command 1"
 1047  25-04-2016 18:20:48 echo "Command 2"
 1048  25-04-2016 18:20:50 echo "Command 3"
 1049  25-04-2016 18:20:51 echo "Command 4"
 1050  25-04-2016 18:20:53 echo "Command 5"
 1051  25-04-2016 18:20:54 echo "Command 6"
 1052  25-04-2016 18:20:56 echo "Command 7"
 1053  25-04-2016 18:20:57 echo "Command 8"
 1054  25-04-2016 18:21:00 echo "Command 9"
 1055  25-04-2016 18:21:02 echo "Command 10"
 1056  25-04-2016 18:21:07 history 11
[18:21:07 jonathag@gb-slo-svb-0221 ~]$ histdel 1049 1051
[18:21:23 jonathag@gb-slo-svb-0221 ~]$ history 8
 1046  25-04-2016 18:20:47 echo "Command 1"
 1047  25-04-2016 18:20:48 echo "Command 2"
 1048  25-04-2016 18:20:50 echo "Command 3"
 1049  25-04-2016 18:20:56 echo "Command 7"
 1050  25-04-2016 18:20:57 echo "Command 8"
 1051  25-04-2016 18:21:00 echo "Command 9"
 1052  25-04-2016 18:21:02 echo "Command 10"
 1053  25-04-2016 18:21:07 history 11

The question was actually to delete the last 10 commands from history, so if you want to save a little effort you could use another function to call the histdel function which does the calculations for you.

histdeln(){

  # Get the current history number
  n=$(history 1 | awk '{print $1}')

  # Call histdel with the appropriate range
  histdel $(( $n - $1 )) $(( $n - 1 ))
  }

This function takes 1 argument, the number of previous history items to delete. So to delete the last 10 commands from history just use histdeln 10.

Zim
  • 410
  • 4
  • 13
JGC
  • 5,725
  • 1
  • 32
  • 30
81

With Bash 5 you can now do a range...Hooray!:

history -d 511-520

or counting backwards 10:

history -d -10--1

Excerpt from Bash 5 Man Page:

'history'

Options, if supplied, have the following meanings:

'-d OFFSET' Delete the history entry at position OFFSET. If OFFSET is positive, it should be specified as it appears when the history is displayed. 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.

Here is my solution for Bash 4. It iteratively deletes a single entry or a range of history starting with lowest index.

delHistory () {
    count=$(( ${2:-$1} - $1 ))
    while [[ $count -ge 0 ]]; do
        history -d "$1"
        ((count--))
    done
}

delHistory 511 520
David Hatch
  • 2,406
  • 1
  • 17
  • 11
  • 2
    this was working, but now I get "bash: history: -10: history position out of range"..I even get that error with `history -d -2`.. I wonder why. This worked for me.. it deletes the last entry `hdl() { history -d $(($HISTCMD - $1))-$(($HISTCMD - 2)) ;}` https://unix.stackexchange.com/a/573258/346155 – alchemy Mar 18 '22 at 20:58
31
for x in `seq $1 $2`
do
  history -d $1
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    Be sure to use the higher number for the first argument or you will delete every other command. E.g. when command 511 is deleted, everything shifts down so 512 becomes the new 511 and 513 is the new 512. Therefor `history -d 511` works as expected, then `history -d 512` deletes what used to be 513, and 512 remains in the history as command 511. Hope that makes sense. – Matthew Dec 08 '15 at 21:12
  • 6
    @Matthew That's not necessary. I'm not deleting `$x` each time through the loop, I'm deleting `$1`. So it first deletes 511,and 512 becomes 511. Then it deletes 511 again, and so on. – Barmar Dec 08 '15 at 21:37
  • @Matthew Notice that I made a similar comment to Tyler's answer. I came up with my solution as a fix for that. – Barmar Dec 08 '15 at 21:38
  • 1
    you are correct, in my haste when wrote this out in a single line in my bash prompt I used `for i in` ... and `history -d $i` and got the results I described in my comment above. Using $1 this absolutely is correct as stated in your original answer. – Matthew Dec 08 '15 at 23:46
26

First, type: history and write down the sequence of line numbers you want to remove.

To clear lines from let's say line 1800 to 1815 write the following in terminal:

$ for line in $(seq 1800 1815) ; do history -d 1800; done

If you want to delete the history for the deletion command, add +1 for 1815 = 1816 and history for that sequence + the deletion command will be deleted.

For example :

$ for line in $(seq 1800 1816) ; do history -d 1800; done
Anthony Geoghegan
  • 11,533
  • 5
  • 49
  • 56
Ghassan Zein
  • 4,089
  • 3
  • 19
  • 30
  • I made an update but still not working correctly in Ubuntu 12.04.. :( It looks like the line number part is not working correctly – Binod Kalathil Apr 13 '16 at 09:23
  • I rejected Binod's suggested edit as it's not a logical error. Ghassan's original code uses the same approach as Barmar's answer – which works. The comments to Barmar's answer explain why the suggestion of replacing 1800 with `$line` deletes *every other line* and then exceeds the desired range. – Anthony Geoghegan Apr 13 '16 at 09:37
22

Combining answers from above:

history -w vi ~/.bash_history history -r

10

I used a combination of solutions shared in this thread to erase the trace in commands history. First, I verified where is saved commands history with:

echo $HISTFILE

I edited the history with:

vi <pathToFile>

After that, I flush current session history buffer with:

history -r && exit

Next time you enter to this session, the last command that you will see on command history is the last that you left on pathToFile.

M. Gleria
  • 468
  • 5
  • 14
  • this works for me , for the answer from @jgc , when i login again to server , history is back again , works only for that logged in session – Yogeshwar Tanwar Feb 17 '20 at 19:41
9

edit:

Changed the braced iterators, good call. Also, call this function with a reverse iterator.

You can probably do something like this:

#!/bin/bash
HISTFILE=~/.bash_history   # if you are running it in a 
                           # non interactive shell history would not work else
set -o history
for i in `seq $1 $2`;
do
    history -d $i
done
history -w

Where you will evoke like this:

./nameOfYourScript 563 514

Notice I haven't put any error checking in for the bounds. I'll leave that as an exercise to the reader.

see also this question

Community
  • 1
  • 1
Tyler Jandreau
  • 4,245
  • 1
  • 22
  • 47
  • 6
    After you delete 510, 511 becomes 510, 512 becomes 511, and so on. So this will delete every other line. – Barmar Feb 07 '13 at 12:12
  • You cannot include variables in brace expansions. – chepner Feb 07 '13 at 18:10
  • `seq 563 514` will print nothing. You need `seq 563 -1 514`. Alternately, you can simply use `history -d $1` with arguments as `514 563` – anishsane Aug 21 '15 at 04:43
9

Maybe will be useful for someone.
When you login to any user of any console/terminal history of your current session exists only in some "buffer" which flushes to ~/.bash_history on your logout.
So, to keep things secret you can just:
history -r && exit
and you will be logged out with all your session's (and only) history cleared ;)

Alex
  • 425
  • 1
  • 6
  • 8
7

Not directly the requested answer, but maybe the root-cause of the question:

You can also prevent commands from even getting into the history, by prefixing them with a space character:

# This command will be in the history
echo Hello world

# This will not
 echo Hello world
Thomas Jacob
  • 618
  • 6
  • 12
3

to delete last 10 entries (based on your example) :

history -d 511 520
Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
2

Short but sweet: for i in {1..10}; do history -d $(($HISTCMD-11)); done

alchemy
  • 954
  • 10
  • 17
1

history -c will clear all histories.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
1
for h in $(seq $(history | tail -1 | awk '{print $1-N}')  $(history | tail -1 | awk '{print $1}') | tac); do history -d $h; done; history -d $(history | tail -1 | awk '{print $1}')

If you want to delete 10 lines then just change the value of N to 10.

Ryan Walker
  • 3,176
  • 1
  • 23
  • 29
1

I use this script to delete last 10 commands in history:

pos=$HISTCMD; start=$(( $pos-11 )); end=$(( $pos-1 )); for i in $(eval echo "{${start}..${end}}"); do history -d $start; done

It uses $HISTCMD environment var to get the history index and uses that to delete last 10 entries in history.

Junaid
  • 3,477
  • 1
  • 24
  • 24
1

I use this (I have bash 4):

histrm() {
    local num=${1:- 1}
    builtin history -d $(builtin history | sed -rn '$s/^[^[:digit:]]+([[:digit:]]+)[^[:digit:]].*$/\1/p')
    (( num-- )) && $FUNCNAME $num
    builtin history -w
}

The builtin history parts as well as the last -w is because I have in place a variation of the famous tricks to share history across terminals and this function would break without those parts. They ensure a call to the real bash history builtin (and not to my own wrapper around it), and to write the history to HISTFILE right after the entries were removed.

However this will work as it is with "normal" history configurations.

You should call it with the number of last entries you want to remove, for example:

histrm 10

Will remove the last 10 entries.

ata
  • 2,045
  • 1
  • 14
  • 19
1
history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;history -d 511;

Brute but functional

Jan Černý
  • 1,268
  • 2
  • 17
  • 31
Daddef
  • 19
  • 1
0

A simple function can kill all by number (though it barfs on errors)

kill_hist() {
    for i in $(echo $@ | sed -e 's/ /\n/g;' | sort -rn | sed -e 's/\n/ /;')
    do
            history -d $i;
    done
}
kill_hist `seq 511 520`
# or kill a few ranges
kill_hist `seq 1001 1010` `seq 1200 1201`
steveo'america
  • 206
  • 1
  • 7
0

Try the following:

for i in {511..520}; do history -d $i; echo "history -d $i"; done
Chris Walsh
  • 3,423
  • 2
  • 42
  • 62
rb1234
  • 37
  • 2
0

the history -d arg takes a range and $HISTCMD is the max number in the history.

This function works to remove the last n entries from history (just pass in the number of history commands to remove like, eg rmhist 5) :

$ rmhist()  { history -d $(($HISTCMD - $1))-$HISTCMD ;}

Or.. Go fancy with an arg like this to remove from a point in history (inclusive) or last 'n' commands:

rmhist() { 
  case $1 in 
    --from|from) local start=$2; ;; 
    --last|last) local start=$(($HISTCMD - $2)) ;; 
    *) echo "Try rmhist --from # or rmhist --last n "; return ;; 
  esac; 
  history -d ${start}-${HISTCMD}
}

The result looks something like this:

 5778  ls /etc
 5779  ls /tmp
 5780  ls /dev
 5781  ll
 5782  cd /tmp
 5783  cd
 5784  history
(base) ~ $ rmhist --last 3
(base) ~ $ history 5
 5778  ls /etc
 5779  ls /tmp
 5780  ls /dev
 5781  ll
 5782  history 5
(base) ~ $ rmhist --from 5780
(base) ~ $ history 5
 5776  history 10
 5777  ls
 5778  ls /etc
 5779  ls /tmp
 5780  history 5
user2711286
  • 141
  • 1
  • 6
0
#delete ten times the last history line    
for i in $(seq 1 10)
do
  n=$(history 1 | awk '{print $1}')
  history -d $n
done
FIBA
  • 101
  • 1
  • 2