Home > other >  How to remove entries with export from bash history?
How to remove entries with export from bash history?

Time:07-31

I'm trying to remove entries from the bash history which contain export. I think I'm not so far from the solution. So far I have:

history | grep export | awk '{print $1}' | sort -r | xargs -I {} bash -c "echo 'Deleting [{}]' && history -d {}"

  • history = get history line id line content
  • grep export = filter on lines containing "export"
  • awk '{print $1}' = print only the line id
  • sort -r = sort line ids in descending order (otherwise when deleting earlier ids, all subsequent ones get shifted)
  • xargs -I {} bash -c "echo 'Deleting [{}]' && history -d {}" = for each line id, run the history delete fn

When I troubleshoot each part of the command I seem to be getting what I need, however overall it's still failing saying the lines I'm trying to delete are out of range.

Can someone please help me finish this command please?

CodePudding user response:

Maybe an easier approach would be to filter and delete directly from the history file.

$ sed -i.bak '/\<export\>/d' "$HISTFILE"

I have wrapped the filtered word in word boundaries, but can be adjusted to suit your filtering requirements.

A backup is also created in case you need to roll back.

$ cat "$HISTFILE" 

will then show you the new history file. If happy with the removed entries, reload history for the changes to take effect globally.

$ history -r

CodePudding user response:

You seem to have multi-line strings that include export in your history. I'll assume that you want to delete the related commands too.

The following solution isn't bullet proof but it should work for most cases:

#1/bin/bash

HISTFILE=~/.bash_history
set -o history

while IFS='' read -r id
do
    echo "deleting $id from history"
    history -d "$id"
done < <(
    set -o history
    history |
    awk '
        /^ *[1-9][0-9]*  / { id = $1 }
        /export/ && !seen[id]   { list[  n] = id }
        END { for (i = n; i >= 1; i--) print list[i] }
    '
)

remark: As you're already using bash and awk you don't need to call sort nor xargs

  • Related