linux - 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
解决方案
调试建议,从此改变:
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
推荐阅读
- java - BinarySearchTree 中的 balance 方法有什么问题?(爪哇)
- reactjs - 如何用子项目构建项目?
- python - 如何在其他文本之间抓取特定文本?
- javascript - 如何通过 GTM 在 Google Analytics 中显示内部用户 ID 而不是客户端 ID(ga cookie)?
- java - 如何在 RestController 中基于 JsonView 使用两个不同的 getter 进行序列化?
- javascript - 在处理所有文件后运行的 Babel 钩子?
- google-cloud-dataflow - 将计时器设置为看到的最小时间戳
- c - 翻转字节,做算术并再次翻转它们
- tableau-api - Tableau - 多变量的堆积条形图
- python - 如何通过 Python 从封闭组中获取 Facebook 反应?