Say you want to automatically start programs when starting up Linux. A quick and easy way to make a script or program start when Linux does is through the init scripts located in the /etc/rc2.d/ directory. These scripts are called in order of priority when Linux enters runlevel 2. Your default runlevel may be different than 2, so be sure to check with the ‘runlevel’ command or in the /etc/inittab. In order for the scripts here to start, they must follow a three-part naming schema. For example: /etc/rc2.d/S10thisscript. This script will Start with priority of 10 when the system enters runlevel 2 and is described as thisscript. The description doesn’t matter, but it is useful to give it a meaningful name. For more information, please see this page.
Here’s a very quick and dirty walkthrough that will change the IP address whenever the system is booted:
echo "ifconfig eth0 192.168.1.102" > /etc/init.d/changeip chmod +x /etc/init.d/changeip ln -s /etc/init.d/changeip /etc/rc2.d/S10changeip
So, you can see that we create a script called changeip in the /etc/init.d/ directory, gave it executable permissions, and then created a symbolic link to /etc/rc2.d/S10changeip so that it will run when the system is started. As a general note, the script can be located anywhere as long as the symbolic link is targeted at /etc/rc2.d/S10changeip.
If you are going to be calling a binary that needs to run in the background, you’ll want to use the
sleep commands like below to avoid having your application be terminated with the init process (the sleep command will prevent the nohup command from being killed before it’s initialized — ironic):
nohup myprog & sleep 1
Along the same lines as the above trick, a script can be made to run whenever a user logs in by placing the name and location of your script into the ~/.profile directory. For example:
# ~/.profile: executed by Bourne-compatible login shells. if [ "$BASH" ]; then if [ -f ~/.bashrc ]; then . ~/.bashrc fi fi mesg n echo "Now running user script..." /home/username/changeip
Note: I’ve just learned that on Debian systems, all you may need to do is create the script, make it executable, and then call the “update-rc.d” command like such:
chmod +x the_script_name update-rc.d the_script_name defaults