Creating startup scripts

From LQWiki
Jump to: navigation, search

On Slackware, startup scripts are located in the /etc/rc.d/ folder, including rc.local. On Red Hat and Fedora, the script rc.local is run after all other rc scripts have run their course.

Automating Basic Startup Commands

If you need a simple command to automatically run when the computer boots up, add the command to your rc.local file. This can often be found at the location /etc/rc.local. For example, you may wish to increase the maximum Shared Memory size. You could add these commands to rc.local:

echo "Increasing Shared Memory Size ..."
echo 1024000000 > /proc/sys/kernel/shmmax

Or activate num lock on the tty terminals 1 to 6 at the local console:

echo "Activating Numlock ..."
for i in 1 2 3 4 5 6; do
        /usr/bin/setleds +num < /dev/tty${i} > /dev/null

Advanced Startup Scripts

When creating your own init scripts, they are essentially just normal bash scripts, with some special comments to make them understandable by applications like chkconfig:

# chkconfig: - 99 01
# description: Starts and stops the D3 Virtual Machine.

Line 1: as normal, we start the script with an interpreter line

Line 2: blank

Line 3: we're telling chkconfig to pay attention. The numbers after the ': - ' are the startup priority and shutdown priority. In this example, this script has the last priority when starting (99) and highest priority when shutting down (01). Remember that this priority is done at a string level, not a numeric level, so 1 and 01 are different. If multiple scripts have the same priority, then they will start within their priority in alphabetical order according the the rest of their name. For example, if we have 2 scripts:


then 'ipsumlorum' will start before 'lorumipsum'

Line 4: a description of what the script is for.

After these 'special' comments, we can have the rest of our scripts. The rest of the script can be anything you like, but normally there are functions created to start and stop the program, and perhaps one to return the status too.

The input from the user / init process is then handled by a simple case block to call the individual functions as required.

Below is an example init script, with a starting priority of 80 and shutdown priority of 45

# chkconfig: - 80 45
# description: Starts and stops myProgram

start() {
        echo -n "Starting myProgram... "
        # Code here to start the program and check it's OK
        echo "OK"
        return 0

stop() {
        echo -n "Stopping myProgram... "
        # Code here to stop the program and check it's dead
        echo "OK"
        return 0

status() {
        # Code here to check the status of the program
        return 0

case "$1" in
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 1

exit $?

See also