首页 > 解决方案 > rc.d 脚本默认给定一个“开始”参数?

问题描述

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

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

当前的 lvl 是:3,参数数量是:1 我在第 10 行。命令是启动

为什么它开始争论而我没有通过任何争论。
函数 start 用于创建文件,函数 stop 用于删除文件,它们
工作正常如果我删除参数数量的测试条件并让脚本在文件处于 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

标签: linuxbashshellsysv

解决方案


调试建议,从此改变:

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;;&caseecase


推荐阅读