How to Write an Auto-Run Script in Linux

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.

To Run on System Boot

Step

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

Step

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:

Step

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

Step

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:

Step

update-rc.d script.sh defaults

Step

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

Step

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

To Run on Device Mount

Step

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.

Step

Run the following command if your device is USB based:

Step

lsusb

Step

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:

Step

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

Step

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.

Step

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:

Step

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