Have script run on startup linux

How to run script on startup using systemd in Linux

Table of Contents

In this article I will share a sample systemd unit file which you can use to run script at startup with systemd without using crontab in RHEL/CentOS 7/8 Linux.

Some more articles on similar topic:

  • How to execute a command or script with systemd at shutdown only and not at reboot in Linux
  • How to execute a command or script with systemd right before login prompt appears on terminal in Linux
  • How to execute a command or script at system startup using systemd without using cronjob in Linux
  • How to execute a command or script after N minutes of boot up (system startup) with systemd in Linux
  • How to halt system reboot or shutdown and read user input during boot up stage in Linux
  • How to execute a command or script using systemd right before shutdown happens in Linux
  • How to run a service as a specific user or group using systemd in Linux

There can be various scenarios when you expect a script or command to be called at startup such as

  • Execute a script after waiting for N minutes of startup
  • Execute a script after all the systemd services are loaded
  • Execute a script immediately after login prompt appears
  • Execute a script just before the login prompt appears

In this article I will cover below two topics as they are almost similar

  • Run script at startup with systemd after network is reachable
  • Execute script at starup after all the systemd services are loaded

I will be using CentOS/RHEL 7/8 Linux node to verify the steps from this article to run script with systemd right before login prompt.

Step 1: Overview on systemd

I hope you are already familiar with below topics

Step 2: Create Sample Script

Now to run script at startup with systemd firstly we need a script or command. For the sake of this article I have create a dummy shell script /tmp/startup_script.sh which we will use for testing this article.

This script will continue to run for 5 minutes and will print an echo statement on the screen every minute as a broadcast message using wall command for all Linux users on the respective node. And at the end of 5th minute it will print a completed broadcast. With this we can also make sure that the script is not killed by systemd if it continues to run for 5 minutes .

Provide executable permission to the script

Enable the service to make sure this is called automatically after reboot

Источник

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

I have a script in a folder:

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:

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

with content like the following

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.

Make it executable.

Configure the init system to run this script at startup.

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

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.

Источник

what is the best way to start a script in boot time on linux

I want to start a script I have on when the system start and looking for the best way, my way is:

systemctl daemon-reload; systemctl enable myscript; systemctl start rmyscript

it’s working good but just wondered if there another and better way.

1 Answer 1

There are a couple of ways to achieve this, but 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 an initscript

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:

Make it executable:

Configure the init system to run this script at startup:

Alternative #2. Add commands to /etc/rc.local

with content like the following:

Alternative #3. Add an Upstart job

with the following content:

You don’t need to be root if 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).

Источник

How to run scripts on start up?

How can I run scripts automatically when Ubuntu starts up so I don’t have to run them manually after startup?

9 Answers 9

One approach is to add an @reboot cron task:

    Running crontab -e will allow you to edit your cron.

Adding a line like this to it:

will execute that script once your computer boots up.

Depending on what sort of scripts you need to run.. For services and the like you should use upstart. But for a user script these should be launched as session scripts by gnome! Have a look under System > Preferences > Startup Applications.

On a side note if you need some scripts to be run on terminal login you can add them to the .bash_login file in your home directory.

For 14.04 and older

A simple command (one which doesn’t need to remain running) could use an Upstart job like:

Save this in a .conf file in /etc/init (if you need it to run as root when the system boots up), or in

/.config/upstart (if you need it to run as your user when you log in).

/.config/upstart . So where are startup applications defined?

You can add commands to /etc/rc.local :

This executes the commands as root.

To execute commands as a specific user, use sudo -i -u ( -i to also run the login shell). For example, to establish a persistent SSH tunnel, where myhost is definde in johndoe s

Читайте также:  Secure boot kali linux

Note that if /etc/rc.local did not exist (as is the case on Ubuntu since 16.04), you need to add a shebang line at the top (e.g. #!/bin/bash ), and ensure the file is executable:

For 15.04 and later:

To run a (short-lived) 1 command at startup using systemd , you can use a systemd unit of type OneShot . For example, create /etc/systemd/system/foo.service containing:

Essentially, this is just converting a typical Upstart job to a systemd one (see Systemd for Upstart users).

You can run multiple commands from the same service file, using multiple ExecStart lines:

The command must always be given with the full path. If any command fails, the rest aren’t run. A — before the path tells systemd to ignore a non-zero exit status (instead of considering it a failure).

For user sessions, you can create the systemd unit in

/.config/systemd instead. This should work with 16.04 onwards, but not earlier releases of Ubuntu with systemd (since those still used Upstart for user sessions). User session units can be controlled with the same commands as with system services, but with the —user option added:

Shell syntax

Note that, unlike Upstart, systemd doesn’t run the Exec* commands through a shell. It performs some limited variable expansion and multiple command (separated by ; ) itself, but that’s about it as far as shell-like syntax goes. For anything more complicated, say redirection or pipes, wrap your command in sh -c ‘. ‘ or bash -c ‘. ‘ .

1 As opposed to long-lived daemons.

There are different ways to automatically run commands:

The upstart system will execute all scripts from which it finds a configuration in directory /etc/init . These scripts will run during system startup (or in response to certain events, e.g., a shutdown request) and so are the place to run commands that do not interact with the user; all servers are started using this mechanism.

You can find a readable introduction to at: http://upstart.ubuntu.com/getting-started.html the man pages man 5 init and man 8 init give you the full details.

A shell script named .gnomerc in your home directory is automatically sourced each time you log in to a GNOME session. You can put arbitrary commands in there; environment variables that you set in this script will be seen by any program that you run in your session.

Note that the session does not start until the .gnomerc script is finished; therefore, if you want to autostart some long-running program, you need to append & to the program invocation, in order to detach it from the running shell.

The menu option System -> Preferences -> Startup Applications allows you to define what applications should be started when your graphical session starts (Ubuntu predefines quite some), and add or remove them to your taste. This has almost the same purpose and scope of the .gnomerc script, except you don’t need to know sh syntax (but neither can you use any sh programming construct).

Источник

Executing Commands and Scripts at Reboot & Startup in Linux

There might arise a need to execute a command or scripts at reboot or every time when we start our system. So how can we do that, in this tutorial we are going to discuss just that. We will discuss how we can make our CentOS/RHEL and Ubuntu systems to execute a command or scripts at reboot or at system startup using two different methods. Both the methods are tested and works just fine,

Method 1 – Using rc.local

In this method, we will use ‘rc.local’ file located in ‘/etc/’ to execute our scripts and commands at startup. We will make an entry to execute the script in the file & every time when our system starts, the script will be executed.

But we will first provide the permissions to make the file /etc/rc.local executable,

$ sudo chmod +x /etc/rc.local

Next we will add the script to be executed in the file,

$ sudo vi /etc/rc.local

& at the bottom of file, add the entry

sh /root/script.sh &

Now save the file & exit. Similarly we can execute a command using rc.local file but we need to make sure that we mention the full path of the command. To locate the full command path, run

$ which command

$ which shutter

/usr/bin/shutter

For CentOS, we use file ‘/etc/rc.d/rc.local’ instead of ‘/etc/rc.local’. We also need to make this file executable before adding any script or command to the file.

Читайте также:  Не работает общий доступ windows 10 ltsc

Note:- When executing a script at startup, make sure that the script ends with ‘exit 0’.

Method 2 – Crontab method

This method is the easiest method of the two methods. We will create a cron job that will wait for 90 seconds after system startup & then will execute the command or script on the system.

To create a cron job, open terminal & run

$ crontab -e

& enter the following line ,

@reboot ( sleep 90 ; sh /location/script.sh )

where /location/script.sh is the location of script to be executed.

So this was our tutorial on how to execute a script or a command when system starts up. Please leave your queries, if any , using the comment box below.

If you think we have helped you or just want to support us, please consider these :-

Linux TechLab is thankful for your continued support.

Share Article:

Shusain

Passionate about Linux & open source. Loves to learn, read & write about Linux as well as new technologies.

Trying to Beta Test Your New App? Consider These Helpful Tips For Success

NC command (NCAT) for beginners

15 Comments

Hello, are the slahes and backslashes correct?
@reboot ( sleep 90 ; sh \location\script.sh )
or
@reboot ( sleep 90 ; sh /location/script.sh )

Thanks for pointing out , it should be ‘/location/script.sh’.
Updating the article.

Hi, Thanks for this helpful information.
I’ve installed TightVNC on my (headless) file server which is running Ubuntu 18.04 LTS 64bit.
I start the vnc server with,
$ vncserver -geometry 1280×720 -depth 24
New ‘X’ desktop is krt1293:1

Starting applications specified in /home/bob/.vnc/xstartup
Log file is /home/bob/.vnc/krt1293:1.log

OK.
I’m accessing it from my main PC (Xubuntu 16.04 LTS 64bit) using Reminna.
I run,

$ ssh -L 5901:localhost:5901 -N -f -l USER IP

I then am able to connect using Remmina with settings,
Protocol: VNC – Virtual Network Computing
Server: localhost:5901

The connection is established and all is working OK to this point.
I then decided to setup so vncserver is started at bootup using a crontab.

Opened user crontab file with,
$ crontab -e
Added the following line at the bottom and saved,
@reboot sleep 90 ; sh /location/script.sh
Rebooted – cron failed to start vncserver
Edited the following line at the bottom and saved,
@reboot sleep 90 ; sh /location/script.sh

Rebooted – cron failed to start vncserver
Edited the following line at the bottom and saved,
@reboot (vncserver -geometry 1280×720 -depth 24 :1)
Rebooted – cron failed to start vncserver
Edited the following line at the bottom and saved,
@reboot ( vncserver -geometry 1280×720 -depth 24 :1 )
Rebooted – cron failed to start vncserver
I added a new job to the crontab to confirm that the crontab is being executed at startup,
@reboot ( touch /home/bob/tmp/cron_test )

The “vncserver” crontab failed, but the “touch” crontab was successful. Any thoughts on what I’m doing wrong?
Harry

Try again with full path to vncserver i.e. ‘/usr/bin/vncserver’. In the meanwhile i will try to replicate it on one of my machines.

I have to activate my wifi hardware each time that I reboot my system with this command ’sudo modprobe -v b43’ and I am looking to make this task easier, do you think that I can give sudo privileges?

thanks for your time and help

A quick Google search with “Persistent Module Loading” as search terms will give you the solution you need.
Also i will be posting an article for the same in coming weeks.

i need to run qt exicutble file in auto boot
crontab -e
@reboot /home/ssbc/Desktop/layout1

layout1 is qt exe file

Hi, how do you exit the crontab editor?

:wq, like we exit out in vi/vim editor.

If the script.sh file is executable, is the sh command necessary?
Would @reboot ( sleep 90 ; /location/script.sh ) work?

I need to run a script at startup, the script is located in root directory and in crontab I have added the line @reboot /root/vm_subnet.sh
but it does not run the script at reboot or startup (i guess they are both the same from a boot-up cycle POV). Am I doing something wrong here? Any syggestions?

crontab is user-dependent / user-based. Does your user have root access?

Its user dependent but to be able run scripts on startup you should have root access.

crontab is user-dependent / user-based. Does your user have root access?

Its user dependent but to be able run scripts on startup you should have root access.

Источник

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