Running script at before halt time

I know adding script in startup time. Is it possible, adding script in system shutdown time? For an example Whenever a user, shutdown their PC, I want a history -c command will run in the background so that the user’s previous worked commands can be erasing in the terminal.
Is it possible?

@Buvanesh_Kumar

To run a script/command at shutdown/reboot, you need to take care of three things.

1. Find your Run Level
If you are on a Debian and alike system, your runlevel should be

RunLevel 0 : Halt the System
RunLevel 1 : Single User Mode aka Minimal Mode
RunLevel 2 - 5 : Multiuser Mode
RunLevel 6 : Reboot the System

Find the RunLevel as per your distribution. The rest of the below things to do is based upon above RunLevels.

2. put script to /etc/init.d and create symbolic link for System Halt
In the most general case script is stored in /etc/init.d folder and symbolic links are created in respected runlevel directories.

so to add a script say (custom_shut.sh) to execute automatically at shutdown, put the script in /etc/init.d folder and then create symbolic link (use ‘ln -s’ command) to /etc/rc0.d (0 is the runlevel to halt the system in my case).

3. put script to /etc/init.d and create symbolic link for System Reboot
Optionally if you want to run the script at reboot as well, create a symbolic link to /etc/rc6.d directory.

** All the above action needs root previledge, Don’t forget to su/sudo.

2 Likes

To answer your question,
I need to know what is your shell? is it bash?
where is your complete script?
Did you put #!/bin/bash at the beginning?

Please post question complete in all aspect.

1 Like

my shell is bash.
No i did not add #!/bin/bash at beginning.
my script only have

history -c

Update:
I added #!/bin/bash at beginning. still same problem

I don’t know if doing the same thing at reboot would satisfy your requirement, but adding a @reboot cron job can accomplish this without much hassle.

@reboot history -c

Hope it helps.

3 Likes

I think the problem is not the way you do it:
@gacanepa said: @reboot history -c. It’s right. But it only works with your current ssh or tty session, when run as crontab it does nothing.