为什么我的rc.d脚本被赋予“开始”或“停止”参数?

时间:2018-10-14 23:32:45

标签: linux bash shell sysv

我的目标是提供一个bash脚本服务,在运行级别为5时创建一个文件,并在运行级别为3时删除该文件。

我遇到的问题是当我达到运行级别3时。我得到了:

  

当前lvl是:3,参数数量是:1我在第10行   。命令是开始

为什么要开始争论,而我没有通过任何争论。
功能启动用于创建文件,功能停止用于删除文件,它们可以正常工作
如果删除参数数量的测试条件,让脚本正常工作,并让脚本仅在文件位于lvl 3时删除文件,

但是它告诉我参数个数为1并且开始的事情并没有引起我的注意。我已经做了很多研究,但没有找到任何解决方案。

#! /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

2 个答案:

答案 0 :(得分:1)

调试建议,从此更改:

echo "The current lvl is : $CURRENT_LVL and number of arguments is : $# "
echo "I am at line 10 . The command is $1"

对此:

echo "The current lvl is : $CURRENT_LVL and number of arguments is : $# "
echo "I am at line 10 . The command is \"$1\", the whole command line is \"$0 $@\""

这不会解决问题,但是它将提供有关实际情况的更多信息。


#Main可以简化。它不会解决任何问题,但是可以使思考变得更容易:

#### Main

case "${1,,}" in
    "")     echo "Entered no arguments."
            case "$CURRENT_LVL" in
              3|5) echo "Entered the if current level ${CURRENT_LVL} statement" ;;&
              5)   start ;;
              3)   stop ;;
            esac  ;;

    start)  if ! [ -e "$FILE" ] ; then
                echo "I am the case statement.the command is $1"
                start
            fi ;;

    stop)   [ -e "$FILE" ] && stop ;;

    *)      echo "Please enter start or stop" ;;
esac

请注意bash 行为${1,,}以小写形式返回$1;;&下降到下一个case测试,而不是跳到ecase

答案 1 :(得分:0)

默认情况下,调用服务以在特定运行级别自动运行时,将为其分配“ start”参数。