Linux run script after reboot

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.

Читайте также:  Linux error exit code

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.

Источник

How to Run a Script on Startup in Ubuntu?

Sometimes, we need to perform specific tasks every time the system starts or reboot the script is executed automatically on startup to avoid the user performing those tasks manually. The startup script allows the user to schedule and automate several tasks simultaneously.

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

To run the script on startup in Ubuntu, the executable files are put in the startup folder to perform a specific task when the system starts. This post will discuss how to modify the system files to run scripts on startup with the help of the following topics:

Method 1: Run Script on Startup Using Systemd File

We can modify the systemd file to run a script on startup by following the below steps:

Step 1: Create a Bash Script

Create a bash script file named “StartScript.sh” to get all the details about the user, which will run automatically on startup:

#!/bin/bash echo "Kernel Version: $(uname -a)" > /etc/kernelinfo.txt

Note: Make sure the script file is executable, using the following command:

Step 2: Create a systemd Service

Create a new startup Systemd File within the “/etc/systemd/system” system file having the “.service” extension.

For instance, /etc/systemd/system/ScriptService.service file is created using the following command in the nano editor:

$ sudo nano /etc/systemd/system/ScriptService.service

Write the below content to run the bash script “StartScript.sh” on startup:

[Unit] Description=Custom Startup Script [Service] ExecStart=/home/ubuntu/StartScript.sh [Install] WantedBy=default.target
  • Unit: It stores the metadata and other information you want to store related to the script.
  • Service: Tells the system to execute the desired service, which will run on startup.
  • Install: Allows the service to run the WantedBy directory at the startup to handle the dependencies.

Step 3; Set Permissions of the Service File

Set the user executable file permissions (in this case, binary mode of permissions) for the Service unit file using the following command:

Note: In binary mode, Read=4, Write=2, and Execute=1.

$ chmod 644 /etc/systemd/system/ScriptService.service

  • 6: Provides read and write permissions to the user.
  • 4: Provides read permissions to the group and others.

Step 4: Enable the Service

Use the below-stated command to enable the customized service (which allows the execution on each startup):

$ systemctl enable ScriptService.service

Every time the system starts/reboots, the script file will execute automatically and display all the user information in the /etc/kernelinfo.txt file.

Method 2: Run Script on Startup Using Cron Job

The cron job can be created to run on startup. For instance, to run a script that executes the user details when the system reboot or restarts, follow the below steps:

Step 1: Open the crontab File

Open the crontab file by running this command in the terminal:

Note: If you are opening the crontab file for the first time, the system will ask you to specify the text editor in which the crontab will be opened. Select the desired editor by entering the number written in front of every editor.

Step 2: Add a cron Job

Add a new crontab job to execute on startup by entering the following code in the crontab file:

Читайте также:  Welcome to My Website!

Note: StartScript.sh is the same script that was used in the last section; provide the full path of the script file.

$ @reboot sudo /home/ubuntu/StartScript.sh &

After adding the code, Press the “Ctrl + O” to save, then “Enter” to save the file name, and then press the “Ctrl + X” keys to exit the editor.

The cron job is successfully saved to run the script (print user details) on startup.

Method 3: Run Script on Startup Using rc.local File

The rc.local file can also be used to run the script on startup. To run the desired script on reboot/startup, use the following steps:

Note: The below first two steps will be performed in case there is no “/etc/rc.local” file which can be checked by using the “ls /etc/rc.local” command. In the absence of this directory, it will show blank output, else the directory path.

Step 1: Create rc.local File

Create the “/etc/rc.local” file in the nano editor using the below-mentioned command:

Press “Ctrl + O” to save the file, then press the “Enter” key to save the anime, and press the “Ctrl + X” key to exit the editor.

Step 2: Create an rc-local Service

Create the rc-local service file to manage this service in the default system file “/etc/systemd” by using this command:

$ sudo nano /etc/systemd/system/rc-local.service

Now, press the “Ctrl + O” to save, the “Enter” and “Ctrl + X” to exit.

Step 3: Make the rc.local File executable

Change the rc.local file permissions to make it executable by running the below command:

Step 4: Edit the rc.local File

Open the rc.local file in the nano editor (to add the startup script) by using the following command:

Add the following command in the rc.local file as shown in the below picture:

Note: Replace the “StartScript.sh” with your desired script file name.

sudo /home/ubuntu/StartScript.sh &

Press the “Ctrl + O” to save, the “Enter” and “Ctrl + X” to exit.

The script is saved in the rc.local file, which will automatically run every time the system reboots/starts.

Conclusion

To run the desired script on startup, several methods are used, which include modifying the “systemd”, “cron”, and “rc.local” files. In the systemd method, the desired script is created, added script as a service, and enabled the service to run on startup. Moreover, the script job is added to the crontab file, and the service is added to the rc.local file to run the scripts on startup. This post has addressed numerous methods to run a script on startup in Ubuntu.

Источник

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