Linux start script on startup

How to Run Script on Startup in Linux

Sometimes you may want to run your shell script on the system startup or when the user logs in. For example when you need to run any desktop application, change screen resolution settings, start the remote desktop service, etc.

You can do this in a few ways. The first way — use the autostart feature in your desktop environment, for example, GNOME or KDE. The second way — use the Systemd initialization system which is used in most distributions nowadays. In this article I will explain how to run script on startup in Linux.

Creating Script for Autostart

Maybe you already have a script that you want to run on startup. But if it is not, or you want to practice with another bash shell script, it is pretty straightforward to create one. Let’s create an example script in the /usr/local/bin directory which prints «Hello world» into a file. This directory usually is used for custom binaries, so you can use it for storing your scripts too. In this article I will use the path to the script /usr/local/losst-script.sh. The following script creates file with the output in the current user home directory.

sudo vi /usr/local/losst-script.sh #!/bin/bash
echo «Hello world» > ~/file

After saving the script, make it executable using the following command:

sudo chmod ugo+x /usr/local/losst-script.sh

You can executable the shell script and ensure that it works. Now let’s have a look at how to add it into the system autostart.

How to Run Script on the System Boot

Systemd does not have any place where you can add scripts that you want to run on the system startup. But you can create systemd unit file which will run your script. Use the following command to do this:

sudo systemctl edit —force —full script.service

The command will open a text editor. Paste these lines into it:

[Unit] Description=My Script Service After=multi-user.target [Service] Type=idle ExecStart=/usr/local/losst-script.sh [Install] WantedBy=multi-user.target

You should set the path to the script or a required command into the ExecStart parameter. Note that I have used the Idle service type here, which means that the process will not fork. Now, let’s add this systemd service to autostart:

sudo systemctl enable srcipt

If Systemd can’t find your new service, update information about systemd configuration files using this simple command:

sudo systemctl daemon-reload

After this, the script will be started on the system startup. Reboot the system and find the file with the «Hello world» content in the /root directory to ensure that everything works fine.

If you prefer to use the old approach to autostart custom scripts with rc.local file, you can create the /etc/rc.local file, make it executable, and use the path to the file into the ExecStart parameter in the unit file. After this, you will be able to use this file as well as before Systemd came.

Читайте также:  Linux ext2 and linux swap

How to Run Script on User Log In

1. GNOME Autostart in GUI

You can configure this using a graphical user interface. Run the Startup Applications utility from the main menu. Also, you can run this utility in the terminal:

Here press the Add button. Then, in a new modal window paste a full path to your script in the Command field. Also, you can choose the path to the script in the filesystem using the Browse button. After this press the Add button at the bottom of the modal window:

The script will be started after GNOME finishes loading. You can reboot the system and ensure that you have the file with the «Hello world» text in your home folder.

2. GNOME Autostart Manually

Everything described in the previous section can be done manually, without the Startup Applications utility. Shortcuts for applications that must be started automatically are located in two directories:

  • /etc/xdg/autostart/ — for all users;
  • ~/.config/autostart/ — for the current user.

Create a new shortcut with the *.desktop extension which will run your script in one of the folders above with the following lines:

vi ~/.config/autostart/script.desktop [Desktop Entry] Name=Script Type=Application Exec=/usr/local/losst-script.sh

Here you should paste the path to the script executable into the Exec field. Then paste the name of the shortcut into the Name field and save the changes. After this, your script will be started automatically as well as in the previous section. The Startup Applications can see this shortcut, so you can manage it there too.

3. Autostart using Systemd

The Systemd initialization system can start a dedicated set of services for each user. You can manage these services using the systemctl utility with the —user option. Use this command to create a new user unit file for your script:

systemctl edit —user —force —full script.service [Unit] Description=My Script Service After=default.target [Service] Type=idle ExecStart=/usr/local/losst-script.sh [Install] WantedBy=default.target

The unit file will be created only for the current user. For this case, it will be placed in the /home/sergiy/.config/systemd/user/script.service file. Pay attention, that multi-user.target here is not available, so you should use default.target. Now, add this unit to autostart:

systemctl enable —user script.service

After this, you can reboot the system and ensure that everything works fine.

Wrapping Up

Now, you have learned how to run a script on startup in Linux. It may be difficult for new users, but you also can read the article about Services Autostart in Linux and How to Manage Services in Linux to understand how it works better.

Found a mistake in the text? Let me know about that. Highlight the text with the mistake and press Ctrl+Enter.

Источник

Run a Script on Startup in Linux

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Читайте также:  Запустить службу postgresql linux

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

In this quick tutorial, we’ll explore different options for executing a script on startup in Linux. This comes in handy in plenty of situations, such as if we want to start a server application automatically.

2. Solutions

Without further ado, let’s create a simple script to execute:

#!/bin/sh echo "Last reboot time: $(date)" > /etc/motd

This piece of code sets the message of the day to be the last reboot time, so that each user can see it after their first login.

Then we’ll save our file and make it executable:

Now that our script is ready, let’s see how to schedule its execution.

2.1. Using cron

Let’s begin with the easiest solution, which involves using cron. In order to do this, we need to edit our crontab file:

Here we’ll add a line using the @reboot expression, which will execute our code once at startup:

@reboot sh /home/ec2-user/reboot_message.sh

This solution is quick and clean, since we don’t have to deal with additional configuration, but not every version of cron supports @reboot.

2.2. Using rc.local

Now let’s consider another solution that takes advantage of the /etc/rc.d/rc.local file. Since this file already runs at startup, we can append a line that invokes our script:

sh /home/ec2-user/reboot_message.sh

In order for this to work, we need to ensure that the rc.local file itself is executable:

2.3. Using init.d

Similar to the previous solution, the /etc/init.d folder contains lifecycle executables of the services managed by the system. We can also add our own by creating an LSB-compliant wrapper that starts our service:

#! /bin/sh # chkconfig: 345 99 10 case "$1" in start) # Executes our script sudo sh /home/ec2-user/reboot_message.sh ;; *) ;; esac exit 0 

This wrapper will launch our code when it’s invoked with the start argument. However, we must include a line with the chkconfig configuration, which contains the service runlevel and the start/stop priority.

After placing the wrapper in the init.d folder, we need to register our service for startup execution:

$ chkconfig --add service_wrapper.sh

Since the chkconfig command isn’t available on Debian systems, update-rc.d can be used as an alternative there:

$ update-rc.d service_wrapper.sh defaults

2.4. Using systemd

Finally, let’s see how to run a script with systemd. Similar to init.d, we need to create a service descriptor, called a unit file, under /etc/systemd/system:

[Unit] Description=Reboot message systemd service. [Service] Type=simple ExecStart=/bin/bash /home/ec2-user/reboot_message.sh [Install] WantedBy=multi-user.target 

The file is organized into different sections:

  • Unit – contains general metadata, like a human-readable description
  • Service – describes the process and daemonizing behavior, along with the command to start the service
  • Install – enables the service to run at startup using the folder specified in WantedBy to handle dependencies

Next, we’ll need to set the file permissions to 644, and enable our service by using systemctl:

$ chmod 644 /etc/systemd/system/reboot_message.service $ systemctl enable reboot_message.service

One thing to keep in mind is that, although many major distributions support systemd, it’s not always available.

3. Conclusion

In this article, we took a look at different ways of executing a script at startup in Linux. Each one of them has its pros and cons, but generally speaking, systemd and cron should be preferred when available. Consequently, rc.local and init.d should be used as fallbacks.

Читайте также:  Yellow dog linux ps3

Источник

How do I run a script at start up? [duplicate]

I need this script to run every time the system starts (even if no one logs in to the system). What do I need to do in order to make this happen?

5 Answers 5

You will need root privileges for any the following. To get root, open a terminal and run the command

and the command prompt will change to ‘#’ indicating that the terminal session has root privileges.

Alternative #1: Add commands to /etc/rc.local

with content like the following:

# This script is executed at the end of each multiuser runlevel /path/to/my/script.sh || exit 1 # Added by me exit 0 

Alternative #2: Add an Upstart job (for systems older than 15.04) (not recommended)

with content like the following

description "my job" start on startup task exec /path/to/my/script.sh 

Official statement from upstart website -> «Project is in maintaince mode only. No new features are being developed and the general advice would be to move over to another minimal init system or systemd.»

Alternative #3: Add an init script (obsolete)

Create a new script in /etc/init.d/myscript .

(Obviously it doesn’t have to be called «myscript».) In this script, do whatever you want to do. Perhaps just run the script you mentioned.

chmod ugo+x /etc/init.d/myscript 

Configure the init system to run this script at startup.

update-rc.d myscript defaults 

It is possible to do the same thing by writing a short Upstart job. Initscripts are still supported, however, and are easy to use.

You don’t need root, or to even login.

You can edit your crontab ( crontab -e ) and create an entry like this:

This way, you can run it as a regular user. @reboot just means it’s run when the computer starts up (not necessarily just when it’s rebooted).

P.S.: Regarding comments that this does not work properly

Some have said that this doesn’t work on Debian-based distros, such as Ubuntu. I have personally successfully used this method on both Ubuntu and Mint. There are a few things to consider, however.

The @reboot jobs will run when the cron daemon starts. I’ve found that on Debian-based distros, this may occur before the /home partition has been mounted. If the script you’re running is in your home folder, it will fail.

Additionally, this isn’t limited to Debian-based distros, but if your home folder is encrypted, it may not be decrypted until after you login. There is probably no way around this.

Also, your network interface may not be up yet, and if the command requires Internet access, it may fail.

Finally, again, this is not limited to Debian-based distros, but cron runs under a much more limited environment than your shell runs under. In particular, the PATH variable has much fewer paths. It is possible that the command being run isn’t found, if it’s in, for example, something like $HOME/.local/bin , which may be in your PATH in your shell session, but not under cron . It’s even possible that the command being run depends on some environment variable that’s not set in cron .

So, there are a number of reasons why your command will to run under cron, but it’s not because @reboot doesn’t work on your distro.

Источник

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