linux – start-stop-restart shell脚本的功能
我是一个
shell脚本新手试图理解一些代码,但有一些线对我来说太复杂了.我正在谈论的那段代码可以在这里找到:
https://gist.github.com/447191
它的目的是启动,停止和重新启动服务器.这是非常标准的东西,所以值得花一些时间来理解它.我评论了那些我不确定其含义或我完全不理解的那些内容,希望somone可以给我一些解释. #!/bin/bash # BASE=/tmp PID=$BASE/app.pid LOG=$BASE/app.log ERROR=$BASE/app-error.log PORT=11211 LISTEN_IP='0.0.0.0' MEM_SIZE=4 CMD='memcached' # Does this mean,that the COMMAND variable can adopt different values,depending on # what is entered as parameter? "memcached" is chosen by default,port,ip address and # memory size are options,but what is -v? COMMAND="$CMD -p $PORT -l $LISTEN_IP -m $MEM_SIZE -v" USR=user status() { echo echo "==== Status" if [ -f $PID ] then echo echo "Pid file: $( cat $PID ) [$PID]" echo # ps -ef: Display uid,pid,parent pid,recent CPU usage,process start time,# controling tty,elapsed CPU usage,and the associated command of all other processes # that are owned by other users. # The rest of this line I don't understand,especially grep -v grep ps -ef | grep -v grep | grep $( cat $PID ) else echo echo "No Pid file" fi } start() { if [ -f $PID ] then echo echo "Already started. PID: [$( cat $PID )]" else echo "==== Start" # Lock file that indicates that no 2nd instance should be started touch $PID # COMMAND is called as background process and ignores SIGHUP signal,writes it's # output to the LOG file. if nohup $COMMAND >>$LOG 2>&1 & # The pid of the last background is saved in the PID file then echo $! >$PID echo "Done." echo "$(date '+%Y-%m-%d %X'): START" >>$LOG else echo "Error... " /bin/rm $PID fi fi } # I don't understand this function :-( kill_cmd() { SIGNAL=""; MSG="Killing " while true do LIST=`ps -ef | grep -v grep | grep $CMD | grep -w $USR | awk '{print $2}'` if [ "$LIST" ] then echo; echo "$MSG $LIST" ; echo echo $LIST | xargs kill $SIGNAL # Why this sleep command? sleep 2 SIGNAL="-9" ; MSG="Killing $SIGNAL" if [ -f $PID ] then /bin/rm $PID fi else echo; echo "All killed..." ; echo break fi done } stop() { echo "==== Stop" if [ -f $PID ] then if kill $( cat $PID ) then echo "Done." echo "$(date '+%Y-%m-%d %X'): STOP" >>$LOG fi /bin/rm $PID kill_cmd else echo "No pid file. Already stopped?" fi } case "$1" in 'start') start ;; 'stop') stop ;; 'restart') stop ; echo "Sleeping..."; sleep 1 ; start ;; 'status') status ;; *) echo echo "Usage: $0 { start | stop | restart | status }" echo exit 1 ;; esac exit 0 解决方法
1)
COMMAND =“$CMD -p $PORT -l $LISTEN_IP -m $MEM_SIZE -v” – 在Unix传统中的-v通常是–verbose的快捷方式.所有这些美元符号都是可变扩展(它们的文本值被插入分配给新变量COMMAND的字符串中). 2) 3)kill_cmd. ps -ef | grep -v grep | grep $CMD | grep -w $USR | awk'{print $2}’打印名为$CMD(‘memcached’)和user $USR(‘user’)的进程的所有PID. grep的-w选项意味着“仅限整个单词”(这不包括所寻求的名称是另一个进程名称的一部分的情况,如’fakememcached’). awk是一个小解释器,最常用于从每行输入中取一个单词数字N(您可以将其视为文本表的一列的选择器).在这种情况下,它会在ps输出行中打印每个第二个字,这意味着每个PID. 如果您有任何其他问题,我将在下面添加答案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |