1, case statement execution process:
Case statements can well replace the multi branch structure in if statements. When using case branch statements, there are several noteworthy features as follows:
-
The first mock exam must be the word "in", and each mode must end with the right bracket). The case must end with the right bracket.
-
Double semicolon ";;" indicates the end of the command sequence;
-
***
- The last ")" indicates the default mode, in which the wildcard is used;
2. Write a system service script with case syntax:
The following sleep command is used to pause the specified time. You can change it to the control command sequence of the corresponding background service according to your own needs.
[root@centos01 ~]# vim myprog #!/bin/bash case "$1" in start) echo -n "Starting sleep service..." if sleep 7200 & then echo "OK" fi ;; stop) echo -n "Stopping sellp Services..." pkill "sleep" &> /dev/null echo "OK" ;; status) if pgrep "sleep" &> /dev/null then echo "sleep The service has started." else echo "sleep The service has stopped." fi ;; restart) $0 stop $0 start ;; \*) echo "usage:$0 { start | stop | status | restart }" esac #Save exit, test script: [root@centos01 ~]# chmod 744 myprog [root@centos01 ~]# ./myprog.sh stop //Stopping sellp service... OK [root@centos01 ~]# ./myprog status sleep The service has started. [root@centos01 ~]# ./myprog start //Starting the sleep service... OK
3. Writing Nginx service control script with case statement
[root@centos01 ~]# vim nginx.sh <! -- create script -- > #!/bin/bash #chkconfig: 35 90 30 #description:nginx server PROG="/usr/local/nginx/sbin/nginx" PIDF="/usr/local/nginx/logs/nginx.pid" case "$1" in start) $PROG echo "Starting Nginx Service!!!" ;; stop) kill -s QUIT $(cat $PIDF) echo "Stopping Nginx Service!!!" ;; restart) echo "Restarting Nginx Service!!!" $0 stop $0 start ;; reload) kill -s HUP $(cat $PIDF) ;; *) echo "Usage:$0 (start|stop|restart|reload)" exit 1 esac exit 0 <!--Save exit, add execution permission--> [root@centos01 ~]# chmod +x nginx.sh <! -- script add execution permission -- > [root@centos01 ~]# / nginx.sh Start <! -- start nginx -- > //Starting Nginx service!!! [root@centos01 ~]# ! net <! -- see if it starts -- > netstat -anptu |grep nginx tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 29899/nginx: master [root@centos01 ~]# / nginx.sh Restart <! -- restart nginx -- > //Restarting Nginx service!!! //Stopping Nginx service!!! //Starting Nginx service!!! [root@centos01 ~]# ! net <! -- check whether Nginx is running -- > netstat -anptu |grep nginx tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 29918/nginx: master [root@centos01 ~]# / nginx.sh Stop <! -- stop nginx -- > //Stopping Nginx service!!! [root@centos01 ~]# ! net <! -- verify that Nginx stops -- > netstat -anptu |grep nginx
————————————Thank you for watching——————————————