Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I delete multiple entries from bash history with this loop

This loop will display what I want to do but if I remove the echo from it, it won't actually delete anything:

history | grep ":[0-5][0-9] ls *$" | cut -c1-5 | 
while read id; do 
    echo history -d $id
done

I've added indentation in order to make it more readable but I am running it as a one-liner from the command line.

I have HISTTIMEFORMAT set so the grep finds the seconds followed by ls followed by an arbitrary number of spaces. Essentially, it's finding anything in history that's just an ls.

This is using bash 4.3.11 on Ubuntu 14.04.3 LTS

like image 742
Stephen Rasku Avatar asked Dec 18 '15 17:12

Stephen Rasku


Video Answer


1 Answers

history -d removes an entry from the in-memory history, and you are running it in a subshell induced by the pipe. That means you are removing a history entry from the subshell's history, not your current shell's history.

Use a process substitution to feed the loop:

while read id; do
    history -d "$id"
done < <(history | grep ":[0-5][0-9] ls *$" | cut -c1-5)

or, if your version of bash is new enough, use the lastpipe option to ensure your while loop is executed in the current shell.

shopt -s lastpipe
history | grep ":[0-5][0-9] ls *$" | cut -c1-5 | 
while read id; do 
    echo history -d $id
done
like image 74
chepner Avatar answered Oct 21 '22 00:10

chepner