How to Write an Auto-Run Script in Linux

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

All of the Linux configuration files are stored in plain-text documents, making them easy to edit. This functionality allows you to add scripts to your computer's startup sequence or device mounting process, effectively making them run automatically when you turn on your PC, plug in your USB device or insert a CD.

Advertisement

To Run on System Boot

Video of the Day

Step 1

Write your script and save it in the /etc/init.d/ directory.

Video of the Day

Step 2

Ensure that the script is executable by running the following command in a shell terminal. Replace "script.sh" with the actual name of your script:

Advertisement

chmod 755 /etc/init.d/script.sh

Step 3

Run the following command, if you use a Debian-based distribution such as Ubuntu or Linux Mint, to create the necessary symbolic links to make the script run on system boot:

Advertisement

update-rc.d script.sh defaults

Again, replace "script.sh" with the actual filename. Run the following commands instead, if you use a non-Debian distro:

chkconfig --add script.sh chkconfig script.sh on

Advertisement

To Run on Device Mount

Step 1

Write your script, make it executable and save it. Any location will do, whether that be on the CD, flash drive or digital camera for which you want it to auto-run or in a location on your hard drive.

Advertisement

Advertisement

Step 2

Run the following command if your device is USB based:

lsusb

This command will output identifying data about all the USB devices currently plugged into your computer. Make a note of the ID data for your device. Create a new file in a text editor and add the following lines of text:

Advertisement

ACTION=="add", SUBSYSTEM=="usb_device", SYSFS{idVendor}=="xxxx", SYSFS{idProduct}=="yyyy", RUN+="/home/linus/script.sh"

Replace "xxxx" with the characters found before the colon in the ID and "yyyy" with those found after it. Replace the path after RUN+= with the path to your script. Save the file as "10-my_autorun.rules" in the /etc/udev/rules.d/ directory. Skip tho the next step if you're using a CD instead of a USB device.

Advertisement

Step 3

Open /etc/udev/rules.d/ in your file manager if you're using a non-USB device, such as a CD or DVD. The directory should contain a file with "cd" in its name; open it. Append the following text to each line the file's contents, replacing the path with that to your actual script, and save it:

RUN+="/home/linus/script.sh"

Advertisement

Advertisement

references

Report an Issue

screenshot of the current page

Screenshot loading...