Search code examples
linuxbashshellsysv

rc.d script given a "start" argument by default?


My objective is to make a bash script service that creates a file when the runlevel is 5 and delete that file when the runlevel is 3.

The problem that I got is when i got to runlevel 3 . I get :

The current lvl is : 3 and number of arguments is : 1 I am at line 10 . The command is start

Why it's getting start argument and I didn't pass any argument.
Function start is for creating the file and function stop is for deleting the file and they are working fine
I can make the script work fine if I remove the test condition on the number of arguments and let the script just delete the file when it's at lvl 3

but the thing that it tells me that the number of argument is 1 and it starts doesn't enter my mind. I have already done much research and I didn't find any solution.

#! /bin/bash
# chkconfig: 35 99 01
# description : some startup script

#### Constants
FILE="/home/ayadi/Desktop/inittp"
CURRENT_LVL="$(runlevel | awk '{print $2}')"
echo "The current lvl is : $CURRENT_LVL and number of arguments is : $# "
echo "I am at line 10 . The command is $1"

#### Functions
start(){
    if ! [[ -f "$FILE" ]];
    then
    touch "$FILE"
    echo "File Created..."
    else
    echo "File Does Exist..."
    fi
}
stop(){
    if [[ -f "$FILE" ]];
    then
    rm "$FILE"
    echo "File Deleted..."
    else
    echo "File Does Not Exist..."
    fi
}

#### Main

if [ $# -eq 0 ]
then
    echo "Entred the arguments -eq 0"
    if [ "$CURRENT_LVL" == "5" ]
    then
        echo "Entred the if current lvl 5 statement"
        start
    fi
    if [ "$CURRENT_LVL" == "3" ]
    then
        echo "Entred the if current lvl 3 statement"
        stop
    fi

else

case "$1" in
    [sS][tT][aA][rR][tT])
        if  ! ([ -e "$FILE" ])
        then
        echo "I am the case statement.the command is $1"
        start
        fi
        ;;
    [sS][tT][oO][pP])
        if [ -e "$FILE" ]
        then
        stop
        fi
        ;;
    *)
        echo "Please enter start or stop"
        ;;
esac

fi

Solution

  • By default, when a service is called to run automatically at a specific run level, it's assigned with "start" argument.