How to Write an Auto-Run Script in Linux

By Mark Keller

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 1

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

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: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:update-rc.d script.sh defaultsAgain, replace "script.sh" with the actual filename. Run the following commands instead, if you use a non-Debian distro:chkconfig --add script.shchkconfig script.sh on

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.

Step 2

Run the following command if your device is USB based:lsusbThis 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: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.

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"