Run command on shutdown linux

commands at ubuntu shutdown

How to execute one or more commands and scripts when ubuntu shutdown? Is there any script like /etc/profile and ~/.bashrc at system starting? I know linux shutdown may have many causes, in addition to dealing with the kill signal, where can I get for this reason?

the question is confusing because of the sub-question. /etc/profile and ~/.bashrc don’t get run at system startup, but rather at user login and shell startup. so, do you mean user logout (which would be ~/bash_logout as susggested in John Laine’s answer)? or do you actually mean system shutdown, which would mean you’re looking for scripts that are analagous to those found in /etc/init.d . and for which there are such scripting options.

@Carina, what are you looking for with respect to details? Details on what the cause of a given system shutdown was or details on how to add hooks to shutdown to execute commands?

3 Answers 3

Is there any script like /etc/profile and ~/.bashrc at system starting?

The SysV Init scripts ( /etc/init.d/* ) are invoked at startup. A trivial/easy way to invoke some activity at system startup is to put it into /etc/init.d/local ( /etc/rc.local for some other distros). See also: RcLocalHowto.

How to execute one or more commands and scripts when ubuntu shutdown?

It sounds as if you want to create a real init script that gets start ed on entering runlevels X-Z and stop ped on exiting them. See also: UbuntuBootupHowto.

I know linux shutdown may have many causes, in addition to dealing with the kill signal, where can I get for this reason?

To do this noninteractively is not straightforward. You can grep through the system logs, looking for indications from shutdown .

There is a ~/.bash_logout file that executes when you log out of Ubuntu 11.04 I am not sure, but assume there is a similar script in 10.04 Hope this helps.

You can put your script in /etc/rc0.d (for halt) and /etc/rc6.d/ (for reboot). Make sure script has executable permission.

There is differents run level :
* 0 System Halt
* 1 Single user
* 2 Full multi-user mode (Default)
* 3-5 Same as 2
* 6 System Reboot

Run level 0 is the system halt condition. When run level 0 is reached all scripts in /etc/rc0.d are exectute.

Run level 6 is used to signal system reboot. This is the same as run level 0 except a reboot is issued at the end of the sequence instead of a power off.

Читайте также:  Linux создать виртуальный сетевой интерфейс

If you want to execute your script on hibernate or on sleep, put your script in /etc/pm/sleep.d/

This is a example of script :

 #!/bin/sh WLANSTATUS=`cat /sys/class/ieee80211/phy*/rfkill*/state` test -z $WLANSTATUS && exit 1 case $1 in hibernate) # Do something before hibernate ;; suspend) # Do something before sleep ;; thaw) # Do something after hibernate ;; resume) # Do something after sleep if [ $WLANSTATUS = 0 ]; then echo 0 > /sys/devices/platform/asus_laptop/wlan elif [ $WLANSTATUS = 1 ]; then echo 1 > /sys/devices/platform/asus_laptop/wlan fi ;; *) echo "somebody is calling me totally wrong." ;; esac 

Источник

How to Run a Script Before Shutdown Under Systemd

Modern Linux systems use systemd to manage daemons and system settings. Systemd is a service manager and initialization system, which took over from SysvInit and has been around for nearly a decade now.

It performs various tasks such as managing daemons (starting, stopping, disabling, and enabling services), snapshot support, and process tracking among others. Currently, it is the default initialization system on most Linux distributions.

You can easily create a custom script that can run as a systemd service. In this guide, we will look at how you can run a script in a systemd just before the system shuts down on a Linux system.

For demonstration purposes, we are using the Rocky Linux 8 server.

Step 1: Create a Sample Script

The first step is to create a shell script that will be executed before shutdown. For demonstration purposes, we will create a simple shell script called sample_script.sh that delays the shutdown of the system by 30 seconds.

To run the script right before the system powers off, you need to place the script in the /usr/lib/systemd/system-shutdown directory. Before executing the actual shutdown, all the binary executables in the /usr/lib/systemd/system-shutdown directory will be executed in parallel.

The execution of the action is not continued until all executable files are done.

$ sudo vim /usr/lib/systemd/system-shutdown/sample_script.sh

The simple shell script that delays the system from shutting down by 30 seconds looks as shown below.

#!/bin/bash # A script that forces the system to wait for 30 seconds before shutdown sleep 30

Save and Exit the file. Next, make the script executable.

$ sudo chmod u+x /usr/lib/systemd/system-shutdown/sample_script.sh

Step 2: Create a Systemd Unit File to Run Shell Script

The next step is to create a systemd unit file to run the shell script before the system power-off. We will create the execute-before-shutdown.service systemd service file as shown.

$ sudo vim /etc/systemd/system/execute-before-shutdown.service

Paste the following lines of code.

[Unit] Description=Execute custom script before system poweroff DefaultDependencies=no Before=shutdown.target [Service] Type=oneshot ExecStart=/usr/lib/systemd/system-shutdown/sample_script.sh TimeoutStartSec=0 [Install] WantedBy=shutdown.target

The crucial task here is done by the Before=shutdown.target and TimeoutStartSec=0 directives.

Save the changes and Exit the file. Thereafter, refresh the systemd configuration file and enable the script to automatically start the next time the system is powered on.

$ sudo systemctl daemon-reload $ sudo systemctl enable execute-before-shutdown.service --now

Step 3: Confirm Systemd Unit File

To confirm that the script is running before the system powers off, simply run the following shutdown command as shown:

Читайте также:  Sangoma linux 7 freepbx login

You’ll observe that the shutdown process will be delayed by 30 seconds before the system eventually goes off.

Conclusion

We hope that the steps outlined in this guide have given you a bearing on how you can go about running a shell script using a systemd on a Linux system.

Источник

Execute a script upon logout/reboot/shutdown in Ubuntu

I’d like to run a .sh file using bash on logout and shutdown of Ubuntu. I have searched up and down the web and have found only fixes for KDE and GNOME. The script is simple, I just need to know if I can add the line of code to the «logoff/shutdown» file or if I need to reference it in another script.

2 Answers 2

How to do it with systemd

If you find this thread after June 2016, Ubuntu and its derivatives including Mint will be using systemd to control system initialization and shutdown. I had problems with the old approach so researched the systemd way.

With systemd you create one or two files to call your scripts using the templates below, and execute a command. Simple.

GUI Version

First create the scripts you want to run at startup and/or shutdown. I created .scopening_atstart and .scfullcopy_atend.

Then make sure that they are both executable by right clicking the file, selecting properties and making sure that, under permissions, you have ticked Allow executing file as a program.

The two files I created populate and save the contents of a ramdisk. They also create a file in my home directory to prove that the service is working. They were of the form:

#!/bin/sh cp -pru /home/john/zRamdisk/subdirectory1/* /home/john/.wine/drive_c/subdirectory1/ rm /home/john/stop_time date +%D' '%T > /home/john/stop_time 

Then I opened my file manager as root, opened /etc/systemd/system and created a file startup.service and a file save-ramdisk.service. Obviously you can choose your own names and generic names could have included a startup file called johns_start.service and a shutdown file called johns_shutdown.service. Just don’t pick existing service names.

[Unit] Description=Startup Applications [Service] Type=oneshot RemainAfterExit=false ExecStart=/home/john/.scopening_atstart [Install] WantedBy=multi-user.target 
[Unit] Description=Save Ramdisk to Wine drive C [Service] Type=oneshot RemainAfterExit=true ExecStart=/bin/true ExecStop=/home/john/.scfullcopy_atend [Install] WantedBy=multi-user.target 

You can use the same service files, substituting the full path of your executable script for mine.

Finally for each one execute the command systemctl enable your_files_name (but without the suffix service). So my first one was systemctl enable startup

Reboot the computer once to start the services. The start service will be executed whenever systemd enters the multi-user target and the stop service when it exits the multi-user target. Alternative service files with different activation conditions will be described below.

Читайте также:  Узнать адрес файла линукс

CLI (Command Line) Version

This description assumes that you operate from your home directory rather than /home/john, use sudo as needed, and your choice of editor where I write vim or svim.

Create startup and shutdown shell scripts with the first line #!/bin/sh and make them executable using chmod +x my_new_filename .

Create two files as above, or in this example, one file to handle startup and shutdown tasks. I will execute scripts in my home directory but @don_crissti showed some alternatives at Stack Exchange.

svim /etc/systemd/system/start_and_stop.service 

and copy in the file content:

[Unit] Description=Run Scripts at Start and Stop [Service] Type=oneshot RemainAfterExit=true ExecStart=/home/john/.startup_commands #your paths and filenames ExecStop=/home/john/.shutdown_commands [Install] WantedBy=multi-user.target 

Then Enable the Service with the command:

systemctl enable start_and_stop 

and reboot your system after which the services will be active. The commands systemctl is-enabled start_and_stop and systemctl is-active start_and_stop can be used in monitoring your new services.

Changing the Trigger Conditions for Shutdown

The files above all use the open or close of the multi-user environment to initiate running the scripts. The file below uses the beginning of four potential shutdown processes to initiate its scripts. Adding or removing the targets on the Before line + the WantedBy line will let you make finer distinctions:

This file was proposed in an answer at Unix & Linux by @Matthias but I was unable to get it to run until I added an Install section.

Again, edit the script in /etc/systemd/service/ and enable it using systemctl enable your_file_name . When I changed the targets I used the systemclt disable file_name command and then re-enabled it which symlinked it to the target directories. Reboot and the service will be operating.

[Unit] Description=Do something required DefaultDependencies=no Before=shutdown.target reboot.target halt.target # This works because it is installed in the target and will be # executed before the target state is entered # Also consider kexec.target [Service] Type=oneshot ExecStart=/home/john/.my_script #your path and filename [Install] WantedBy=halt.target reboot.target shutdown.target 

Debugging

I recently (2020) did a little distro hopping, first to KDE Neon where I discovered that although KDE is light on memory, its cpu usage was considerably higher than mint, and then to Fedora 33 XFCE.

With the second, neither of these scripts worked. So I followed the hints and used systemctl status and journalctl -xe to find the issues. It turned out that something didn’t have permission to run the scripts in my home directory. I experimented unsuccessfully until I changed the invocation to:

ExecStart=/usr/bin/bash /home/john/.scopening_atstart 

This may help someone; but be aware that your system may be using /bin/bash so check your file names and paths.

Источник

Оцените статью
Adblock
detector