Verified Methods to Autorun a Script on Startup

How Can I Run a Command after Boot/Startup in Linux?

Tools or programs called Linux startup scripts are launched by the kernel each time your computer restarts.

Once the system has been booted, users can use any Linux run command on startup to configure programs or carry out specific tasks.

To run script at startup Linux or command, you can use 7 different methods:

  1. /etc/rc.d/rc.local File (rc.local)
  2. Cron Job
  3. systemd service unit
  4. init.d
  5. .bashrc or .bash_profile
  6. Upstart
  7. Startup Applications

After buying Linux VPS and choosing your considered distribution, one of the interesting activities is that you have the option of instructing the operating system to carry out certain tasks at boot up, log on, and log out.

1. Install and Use rc.local file to AutoRun a Script on Startup in Linux

A sequence of rc scripts is run throughout each run level to prepare the system for use or a shutdown.

On contemporary Linux distributions, the rc.local script file might not be accessible by default, so you need to configure it manually.

The system administrator will be granted access to run the rc.local script. Consequently, running a script or command as root is simpler.

  • First, add a simple command to the script that you consider executing once the system starts up:
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Ensure that the script will "exit 0" on success or any other
# value on error.
#
# To enable or disable this script, just change the execution
# bits.
#
# By default, this script does nothing.
pgrep -x $(teamviewerd) || teamviewerd
exit 0

We added a line to the script that would launch the TeamViewer daemon as soon as the system boots up.

Keep in mind that orders sent after exit 0 won’t be carried out. Even if the script’s commands are valid, this can happen occasionally.

In that scenario, you should look at the file’s execution permissions and adjust them as necessary.

You can run the rc.local script at startup if you make a straightforward “rc-local” systemd process.

  • To do this, create a new file in the /etc/systemd/system/rc-local.service and put the following contents in the file:
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

 

[Install]
WantedBy=multi-user.target
  • Then, you need to use systemctl to activate this service after saving the file.
$ systemctl enable rc.local

Create the rc.local file and grant it the necessary permissions after enabling the service.

Note: This method also works on the systemd system.

2. Install and Use Cron Job to Run a Script on Startup in Linux

A file called a crontab provides a collection of commands that can be programmed to run regularly. The cron jobs that we define in this file are the tasks.

A cron daemon, which is installed on the majority of distributions, typically runs them.

There are various cron applications, all of which operate in the same manner and make use of the same crontab format.

You must decide which one to use and how to set it up.

# apt install cronie
# yum install cronie
  • Once the installation is finished, proceed to check it:
$ crond -V
  • The crond service, which is essentially the daemon that will run when the system boots up, must now be enabled. So, type:
# systemctl enable crond

In this way, you can schedule cron jobs in the crontab from now on.

One or more lines can make up a simple crontab. Each line represents a routine task that is completed.

  • Let’s use the crontab command to construct a crontab:
$ crontab -e
  • It should be an empty file first. To let it run each time the system starts up, use the commands below:
@reboot pulseaudio -k && pulseaudio
@reboot redshift -c ~/.config/redshift/config.conf

The time field and the command field are the two fields that make up a crontab entry. When to execute the associated command is specified by the time field.

We added the symbol @reboot to our crontab to indicate that we want the actions to be executed when the system boots up. The above commands will be carried out as regular users.

The -e option instructs crontab to alter the crontab for the current user.

Run the crontab command as root to create a new crontab file specifically for the root user if you want to execute commands as root.

  • To create a task that runs a shell script as root on start-up, type:
$ sudo crontab -e

@reboot . /root/upgrade-system.sh

If you wish to schedule the script to run at a different time or interval, @reboot can also be changed to a certain time or period.

3. Install and Use systemd to Run a Script on Startup in Linux

Systemd is the init and service manager used by the majority of popular Linux distributions.

It is a component of all widely used Linux distributions, including Fedora, Ubuntu, Mint, Debian, and others.

On startup, systemd has a unique method for running customized scripts.

To create the Start-Up script, first, you need a script file with the command(s) you want to run when the computer starts up.

This file will later be designated to operate in a unique systemd service.

  • Create a script file that essentially launches a notification daemon now and make sure to execute this script:
pgrep dunst || setsid -f dunst

As soon as your script is complete, you must establish a systemd service that uses it as a source.

  • So let’s start by making a startup.service file in the /lib/systemd/system directory:
$ touch /lib/systemd/system/startup.service
  • In this way, you can create a systemd service. Then, define your service in this file:
[Unit]
Description=Startup Script
[Service]
ExecStart=/root/.local/bin/startup.sh
[Install]
WantedBy=multi-user.target

The location of our start-up script can be specified by modifying the ExecStart column.

  • Save the file when finished, then turn on the service so that it starts up with our computer:
# systemctl enable startup.service --now

We’ve introduced the - now option and systemd will now enable and start this service.

The same applies to creating many services that will launch at startup and serve various functions.

  • For Linux run script on startup with systemd, you 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 document is divided into several sections:

  • Unit – includes generic metadata, such as a description that can be read by humans.
  • Service – provides information about the demonizing process and the command to start the service.
  • Install- allows the service to Linux execute commands on startup while handling dependencies using the folder specified in WantedBy.
  • The next step is to use systemctl to enable our service and set the file permissions to 644.
$ chmod 644 /etc/systemd/system/reboot_message.service
$ systemctl enable reboot_message.service

4. Using init.d to Run a Script on Startup in Linux

The /etc/init.d folder houses lifecycle executables for the services that the system manages, just like the rc.local arrangement.

  • By developing an LSB-compliant wrapper that launches our service, you may also add your own:
#! /bin/sh
# chkconfig: 345 99 10
case "$1" in
  start)
    # Executes our script
    sudo sh /home/ec2-user/reboot_message.sh
    ;;
  *)
    ;;
esac
exit 0

When this wrapper is called with the start argument, our code will run.

A line with the chkconfig setting, which specifies the service runlevel and the start/stop priority, must nevertheless be added.

  • Once the wrapper has been added to the init.d folder, you must configure your service to run at startup:
$ chkconfig --add service_wrapper.sh
  • Debian systems can use update-rc.d as a substitute as the chkconfig command isn’t accessible there:
$ update-rc.d service_wrapper.sh defaults

5. Using .bashrc or .bash_profile to Run a Script on Startup in Linux

  • For the script to execute on each terminal login, add the command in your .bashrc or .bash_profile.
  • Use .bash_profile or .bash_logout to run a script upon login or logout, respectively. The latter file will probably need to be manually created.
  • To get started, simply add a line to each file’s bottom that invokes your script in the same way as before.

6. Using Upstart to Run a Script on Startup in Linux

Numerous issues related to system V init are diminished and a great deal of customization is offered by the Upstart daemon.

Upstart provides a flexible event-driven architecture and does not rely on obscure scripts to load services at startup.

As an illustration, the echo command is executed upon system startup by the following Upstart service.

In your /etc/init directory, first create the configuration file with a.end suffix.

  • Since they are separate Linux file system directories, do not confuse them with /etc/init.d.
$ nano test.conf

description "testing Linux startup commands"

start on runlevel [2345]
stop on runlevel [!2345]

expect fork

respawn
exec echo "This is a test run!"

7. Using Startup Applications to Run a Script on Startup in Linux

With the help of the GUI tool Startup Applications Preferences, users in modern Linux distributions can define startup scripts or commands.

  • Go to Activities > Type Startup > Select Startup Applications Preferences to locate it.

Using Startup Applications to Run a Script on Startup in Linux

  • Click the Add button in the sidebar once it is open. A new prompt will pop up, allowing you to add the startup script Linux or command.
  • Select your script by clicking Browse, then enter a brief description in the comment field. Don’t forget to give the position a name.
  • To finish the process, click Add at the very end.

add linux startup scripts program

That’s that. At the end of all the above parts, you can restart your system to test that the script is being run on startup.

How do I Run a Script on Startup Linux?

To automate tasks and configure settings, you can run script on startup Linux.

Using the solutions below would be helpful to achieve this purpose:

  • cron (preferred)
  • rc.local (used as fallbacks)
  • init.d (used as fallbacks)
  • systemd (preferred)

How do I Automatically Run a Script in Linux?

Autorun script on startup Linux is explained below:

#!/bin/bash
while [ true ] 
do
    currentoutput="$(lsusb)"
    if [ "$currentoutput" != "$lastoutput" ]
    then
        echo "" date and Time >> test.log
        date +%x_r >> test.log
        lastoutput="$(lsusb)"
        lsusb >> test.log
    fi
    sleep 5
done

It stores the last output of lsusb in $lastoutput and appends if they’re not equal.

Also, you can use the Systemd to automate Linux scripts and commands on startup and use the Linux autostart script:

mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/update-notifier.service

Paste the command below once the nano editor is opened:

[unit]
Description=Reminder to Update System
PartOf=graphical-session-target

[Service]
ExecStart=bash -c 'sleep 50; notify-send "Please, Update your System Now"
Type=oneshot

[Install]
WantedBy=graphical-session.target

To make it executable, run the following commands:

chmod 644 ~/.config/systemd/user/update-notifier.service
systemctl --user enable update-notifier.service
systemctl --user daemon-reload
reboot

How do I Run a bash Script at Startup?

For example, if this is your /etc/rc.local and you have tried chmod +x /etc/rc.local.

Then, run:

$ cat /etc/rc.local
#!/bin/bash
touch /var/lock/subsys/local
echo "hickory stick"

To get this log you viewed after booting your system via bash, run:

$ logger hi

Then, you can then see it in your /var/log/messages or /var/log/syslog or journal -xef.

$ journalctl -xef

To capture output from commands in the script, type:

$ cat /etc/rc.local
#!/bin/bash
touch /var/lock/subsys/local
echo "hickory stick" | logger

Now, after reboot:

$ journalctl -xef

You must see your message there via the logger that you added to /etc/rc.local.

Where are Startup Scripts in Linux?

Startup scripts are critical to the Linux run script on boot because they initialize environment variables, system services, and other components.

The startup scripts can be located in the below destinations which you can select the one that meets your needs:

  • /etc/profile
  • /etc/profile.d
  • ~/.bash_profile or $HOME/.bash_profile
  • /etc/init and /etc/init.d
  • /etc/init/rc-sysinit.conf
  • /etc/default

How do I Make a Script Executable in Linux?

There will be two methods:

First:

Use the command below to make the script executable for everyone and replace <script-file> with your considered script name:

 chmod +x <script-file>

Second:

If you prefer to let certain user or group, use the command below:

chmod <class> +x <script-file>

It restricts execution to your considered users or groups. Do not forget to replace <script-file> with your actual script name.

How to Use Script Linux Command?

The script command on Linux enables you to view the terminal activities that this tool has captured.

  1. Opening a terminal and running script will start a script in Linux and you can run any commands you want.
  2. The captured information such as input and output will be saved in the typescript file. Running the exit command you can stop recording.
  3. To view the recorded script, use the command cat typescript.
  4. Use the chmod +x typescript command to make the script executable.

How do I Run a Program on Startup in Ubuntu?

There are three suggested methods to run a program on startup in Ubuntu:

  1. Search and launch the ‘’Startup Applications’’ tool.
  2. Using systemd  (If you are an Advanced user)
  3. Using cron jobs.

As you see, systemd and corn are the Ubuntu run commands on startup.

Ubuntu run script on startup allows you to run scripts automatically when your Ubuntu system starts up.

How do I Run a Script in Linux bash?

There are two methods to run a script in Linux bash:

  • Check for Executable Permissions (No Interpreter)

To use execute permissions for running a bash script in Linux, use the command below and replace your_script.sh with the actual name of your script:

chmod +x your_script.sh

For Linux execute script on startup, type

./myscript.sh
  • Using an Interpreter:

Every scripting language has an interpreter that runs script files line by line. The script’s execution ends at that line if there is an error.

You can call the shell you’re using for scripts written in Bash.

If you have developed a Bash script, you may run it by typing either sh or bash followed by the script name:

bash your_script.sh

OR

sh your_script.sh

When utilizing an interpreter, there is no need to modify the file’s permissions. Don’t forget to substitute the true name of your script for your_script.sh.

FAQ

If you are unsure, it's a good idea to examine the documentation or speak with an expert. The process for running script on startup may differ based on the Linux distribution you are using.

Your choice of approach will be influenced by the particulars of your system and the script you're attempting to execute. It is crucial to remember that the script's path must be its complete path and not a relative path. You should also confirm that the script has execute permission.

This specific string enables users to run any command or script at boot time.

Conclusion

The methods of Linux run shell script on startup help you find the most suitable way of executing a command or script at reboot or startup in Linux.

Run command on startup Linux has advantages and disadvantages, systemd and cron should generally be preferred when they are available.

It also works for Debian run command on boot. Rc.local and init.d ought to be used as fallbacks as a result.