为什么我不能通过此循环从bash历史记录中删除多个条目 [英] Why can't I delete multiple entries from bash history with this loop

查看:91
本文介绍了为什么我不能通过此循环从bash历史记录中删除多个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此循环将显示我要执行的操作,但是如果我从中删除echo,它实际上不会删除任何内容:

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.

我设置了HISTTIMEFORMAT,因此grep会找到秒数,然后是ls,再加上任意数量的空格.本质上,它在历史中发现的只是ls的任何内容.

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.

这是在Ubuntu 14.04.3 LTS上使用bash 4.3.11

推荐答案

history -d从内存历史记录中删除一个条目,然后在由管道引起的子外壳中运行它.这意味着您将从子shell的历史记录中删除历史记录条目,而不是当前shell的历史记录.

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)

,或者,如果您的bash版本足够新,请使用lastpipe选项以确保while循环在当前shell中执行.

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

这篇关于为什么我不能通过此循环从bash历史记录中删除多个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆