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

若如初见. 提交于 2020-07-08 20:50:33

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/34360534/why-cant-i-delete-multiple-entries-from-bash-history-with-this-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!