2

I want to make a bash script that clears the history i.e. works similarly as the command

history -c

So I started with the following code:-

#!/bin/bash
history     #displaying history
history -c  #clearing history

None of them worked. On some searching around, I came to know that bash disables history in non-interactive shells by default, but we can turn it on. So after editing I tried the following code :-

#!/bin/bash
HISTFILE=~/.bash_history   # Or wherever you bash history file lives
set -o history             # enable history
history
history -c

It shows the output :-

[root@localhost lib]# bash a.sh
1  history
[root@localhost lib]#

And besides that the hisory -c command did not work. Because I am still getting the history of commands when I type history. This means both history and history -c didnt work inside the bash script.

How should we use it then?

EDIT 1- I want to delete the history of the current session, it must be stored somewhere. I have tried using commands like the following but to no effect:-

cat /dev/null > ~/.bash_history && history -c && exit


cat /dev/null > ~/.bash_history

P.S.-This is not a duplicate question. Please try to understand the difference before marking it as duplicate. I want to clear the history of the current session through a script . I don't care if it is written back or whatever. The other question is about to permanently delete the history. It has nothing to do with the script or through other terminal.

2 Answers2

1

You can't delete history like this as it will delete the history of current session.

If you wan to clear your history using script use following command in your script

> ~/.bash_history

It is enough to clear all your bash history .

g_p
  • 19,034
  • 6
  • 59
  • 69
0

I think that

history -c 

will only clear the history inside the seesion associated with the script This example:

#!/bin/bash
HISTFILE=~/.bash_history   # Or wherever you bash history file lives
set -o history             # enable history
uname -a > /dev/null
history
history -c
history

shows the output:

....
500  history
501  uname -a > /dev/null
502  history
4  history

which is what one expects.

If you want to erase the history, try

> $HISTFILE
Gremlin
  • 747
  • 7
  • 18