2

I have a executable bash script (.bash_history_cleaner) which cleans my bash history

#!/bin/bash
cat /dev/null > ~/.bash_history && history -c && exit

I want to execute this script on system shutdown or restart and followed this answer which uses systemd with service name as bash_history_cleaner.service and enabled it in systemctl. The service is up and running,

[Unit]
Description=Bash History Cleaner

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/home/eka/Scripts/.bash_history_cleaner

[Install]
WantedBy=multi-user.target

Its intended behaviour should be to clean my bash history when either shutdown or restart. But its not working, I shutdown and restared the system many times but the script is not executed. How do we execute a bash script before shutdown using systemd?

  • What's the goal of cat /dev/null > vs echo "" >? Does the script work when you run it directly, ie: bash /home/eka/Scripts/.bash_history_cleaner? – earthmeLon Jun 22 at 1:26
  • 2
    Are you implementing this as a system systemd unit? if so, ~/ is not going to resolve to your user's home directory – steeldriver Jun 22 at 1:28
  • @steeldriver you are correct it was not resolving I had to give the full path – Eka Jun 22 at 3:07
  • @earthmeLon you can even skip cat altogether and have it just like so > /path/to/file – Dan Jul 27 at 22:30
1

Why not take advantage of the Linux system and it's /tmp directory to store your .bash_history in a more volatile place?

To change the location of your .bash_history file, you need to set the HISTFILE variable. To have the file deleted every reboot, place the file in the /tmp/ directory.

You can add something such as the following to your ~/.bashrc file so that these settings persist:

HISTFILE=/tmp/.bash_history

You can confirm other users cannot read your history by checking out the file permissions of the history file created:

ls -lsa /tmp/.bash_history

This will cause your user's history to be removed upon reboot, but will not affect others. You can set this system level configuration files such as /etc/bash.bashrc if you really want. You can even put /tmp into RAM to ensure it gets cleared.

  • 1
    Your answer is a good solution for his problem, but unfortunately it does notanswer the question in that I am also interested in to know: How to run a systems command on shutdown? – AlexOnLinux Jun 22 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.