Linux 下Shell的学习3-优秀demo详解程序员

优秀的DEMO

cat /etc/init.d/functions   –>里面有颜色定义
cat /etc/rc.d/rc.sysinit
cat /etc/init.d/nfs
cat /etc/init.d/portmap
cat /etc/init.d/httpd

 

0. function文件

Linux 下Shell的学习3-优秀demo详解程序员

  1 # -*-Shell-script-*- 
  2 # 
  3 # functions    This file contains functions to be used by most or all 
  4 #        shell scripts in the /etc/init.d directory. 
  5 # 
  6  
  7 TEXTDOMAIN=initscripts 
  8  
  9 # Make sure umask is sane 
 10 umask 022 
 11  
 12 # Set up a default search path. 
 13 PATH="/sbin:/usr/sbin:/bin:/usr/bin" 
 14 export PATH 
 15  
 16 # Get a sane screen width 
 17 [ -z "${COLUMNS:-}" ] && COLUMNS=80 
 18  
 19 [ -z "${CONSOLETYPE:-}" ] && CONSOLETYPE="$(/sbin/consoletype)" 
 20  
 21 if [ -f /etc/sysconfig/i18n -a -z "${NOLOCALE:-}" -a -z "${LANGSH_SOURCED:-}" ] ; then 
 22   . /etc/profile.d/lang.sh 2>/dev/null 
 23   # avoid propagating LANGSH_SOURCED any further 
 24   unset LANGSH_SOURCED 
 25 fi 
 26  
 27 # Read in our configuration 
 28 if [ -z "${BOOTUP:-}" ]; then 
 29   if [ -f /etc/sysconfig/init ]; then 
 30       . /etc/sysconfig/init 
 31   else 
 32     # This all seem confusing? Look in /etc/sysconfig/init, 
 33     # or in /usr/doc/initscripts-*/sysconfig.txt 
 34     BOOTUP=color 
 35     RES_COL=60 
 36     MOVE_TO_COL="echo -en //033[${RES_COL}G" 
 37     SETCOLOR_SUCCESS="echo -en //033[1;32m" 
 38     SETCOLOR_FAILURE="echo -en //033[1;31m" 
 39     SETCOLOR_WARNING="echo -en //033[1;33m" 
 40     SETCOLOR_NORMAL="echo -en //033[0;39m" 
 41     LOGLEVEL=1 
 42   fi 
 43   if [ "$CONSOLETYPE" = "serial" ]; then 
 44       BOOTUP=serial 
 45       MOVE_TO_COL= 
 46       SETCOLOR_SUCCESS= 
 47       SETCOLOR_FAILURE= 
 48       SETCOLOR_WARNING= 
 49       SETCOLOR_NORMAL= 
 50   fi 
 51 fi 
 52  
 53 # Interpret escape sequences in an fstab entry 
 54 fstab_decode_str() { 
 55     fstab-decode echo "$1" 
 56 } 
 57  
 58 # Check if any of $pid (could be plural) are running 
 59 checkpid() { 
 60     local i 
 61  
 62     for i in $* ; do 
 63         [ -d "/proc/$i" ] && return 0 
 64     done 
 65     return 1 
 66 } 
 67  
 68 __readlink() { 
 69     ls -bl "$@" 2>/dev/null| awk '{ print $NF }' 
 70 } 
 71  
 72 __fgrep() { 
 73     s=$1 
 74     f=$2 
 75     while read line; do 
 76     if strstr "$line" "$s"; then 
 77         echo $line 
 78         return 0 
 79     fi 
 80     done < $f 
 81     return 1 
 82 } 
 83  
 84 # __umount_loop awk_program fstab_file first_msg retry_msg retry_umount_args 
 85 # awk_program should process fstab_file and return a list of fstab-encoded 
 86 # paths; it doesn't have to handle comments in fstab_file. 
 87 __umount_loop() { 
 88     local remaining sig= 
 89     local retry=3 count 
 90  
 91     remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r) 
 92     while [ -n "$remaining" -a "$retry" -gt 0 ]; do 
 93         if [ "$retry" -eq 3 ]; then 
 94             action "$3" fstab-decode umount $remaining 
 95         else 
 96             action "$4" fstab-decode umount $5 $remaining 
 97         fi 
 98         count=4 
 99         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r) 
100         while [ "$count" -gt 0 ]; do 
101             [ -z "$remaining" ] && break 
102             count=$(($count-1)) 
103             usleep 500000 
104             remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r) 
105         done 
106         [ -z "$remaining" ] && break 
107         fstab-decode /sbin/fuser -m $remaining 2>/dev/null  | sed -e "s//b$$/b//" | xargs kill $sig >/dev/null 
108         sleep 3 
109         retry=$(($retry -1)) 
110         sig=-9 
111     done 
112 } 
113  
114 # Similar to __umount loop above, specialized for loopback devices 
115 __umount_loopback_loop() { 
116     local remaining devremaining sig= 
117     local retry=3 
118  
119     remaining=$(awk '$1 ~ /^//dev//loop/ && $2 != "/" {print $2}' /proc/mounts) 
120     devremaining=$(awk '$1 ~ /^//dev//loop/ && $2 != "/" {print $1}' /proc/mounts) 
121     while [ -n "$remaining" -a "$retry" -gt 0 ]; do 
122         if [ "$retry" -eq 3 ]; then 
123             action $"Unmounting loopback filesystems: " / 
124                 fstab-decode umount $remaining 
125         else 
126             action $"Unmounting loopback filesystems (retry):" / 
127                 fstab-decode umount $remaining 
128         fi 
129         for dev in $devremaining ; do 
130             losetup $dev > /dev/null 2>&1 && / 
131                 action $"Detaching loopback device $dev: " / 
132                 losetup -d $dev 
133         done 
134         remaining=$(awk '$1 ~ /^//dev//loop/ && $2 != "/" {print $2}' /proc/mounts) 
135         devremaining=$(awk '$1 ~ /^//dev//loop/ && $2 != "/" {print $1}' /proc/mounts) 
136         [ -z "$remaining" ] && break 
137         fstab-decode /sbin/fuser -k -m $sig $remaining >/dev/null 
138         sleep 3 
139         retry=$(($retry -1)) 
140         sig=-9 
141     done 
142 } 
143  
144 # __proc_pids {program} [pidfile] 
145 # Set $pid to pids from /var/run* for {program}.  $pid should be declared 
146 # local in the caller. 
147 # Returns LSB exit code for the 'status' action. 
148 __pids_var_run() { 
149     local base=${1##*/} 
150     local pid_file=${2:-/var/run/$base.pid} 
151  
152     pid= 
153     if [ -f "$pid_file" ] ; then 
154             local line p 
155  
156         [ ! -r "$pid_file" ] && return 4 # "user had insufficient privilege" 
157         while : ; do 
158             read line 
159             [ -z "$line" ] && break 
160             for p in $line ; do 
161                 [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p" 
162             done 
163         done < "$pid_file" 
164  
165             if [ -n "$pid" ]; then 
166                     return 0 
167             fi 
168         return 1 # "Program is dead and /var/run pid file exists" 
169     fi 
170     return 3 # "Program is not running" 
171 } 
172  
173 # Output PIDs of matching processes, found using pidof 
174 __pids_pidof() { 
175     pidof -c -o $$ -o $PPID -o %PPID -x "$1" || / 
176         pidof -c -o $$ -o $PPID -o %PPID -x "${1##*/}" 
177 } 
178  
179  
180 # A function to start a program. 
181 daemon() { 
182     # Test syntax. 
183     local gotbase= force= nicelevel corelimit 
184     local pid base= user= nice= bg= pid_file= 
185     local cgroup= 
186     nicelevel=0 
187     while [ "$1" != "${1##[-+]}" ]; do 
188       case $1 in 
189         '')    echo $"$0: Usage: daemon [+/-nicelevel] {program}" 
190                return 1;; 
191         --check) 
192            base=$2 
193            gotbase="yes" 
194            shift 2 
195            ;; 
196         --check=?*) 
197                base=${1#--check=} 
198            gotbase="yes" 
199            shift 
200            ;; 
201         --user) 
202            user=$2 
203            shift 2 
204            ;; 
205         --user=?*) 
206                user=${1#--user=} 
207            shift 
208            ;; 
209         --pidfile) 
210            pid_file=$2 
211            shift 2 
212            ;; 
213         --pidfile=?*) 
214            pid_file=${1#--pidfile=} 
215            shift 
216            ;; 
217         --force) 
218                force="force" 
219            shift 
220            ;; 
221         [-+][0-9]*) 
222                nice="nice -n $1" 
223                shift 
224            ;; 
225         *)     echo $"$0: Usage: daemon [+/-nicelevel] {program}" 
226                return 1;; 
227       esac 
228     done 
229  
230         # Save basename. 
231         [ -z "$gotbase" ] && base=${1##*/} 
232  
233         # See if it's already running. Look *only* at the pid file. 
234     __pids_var_run "$base" "$pid_file" 
235  
236     [ -n "$pid" -a -z "$force" ] && return 
237  
238     # make sure it doesn't core dump anywhere unless requested 
239     corelimit="ulimit -S -c ${DAEMON_COREFILE_LIMIT:-0}" 
240      
241     # if they set NICELEVEL in /etc/sysconfig/foo, honor it 
242     [ -n "${NICELEVEL:-}" ] && nice="nice -n $NICELEVEL" 
243      
244     # if they set CGROUP_DAEMON in /etc/sysconfig/foo, honor it 
245     if [ -n "${CGROUP_DAEMON}" ]; then 
246         if [ ! -x /bin/cgexec ]; then 
247             echo -n "Cgroups not installed"; warning 
248             echo 
249         else 
250             cgroup="/bin/cgexec"; 
251             for i in $CGROUP_DAEMON; do 
252                 cgroup="$cgroup -g $i"; 
253             done 
254         fi 
255     fi 
256  
257     # Echo daemon 
258         [ "${BOOTUP:-}" = "verbose" -a -z "${LSB:-}" ] && echo -n " $base" 
259  
260     # And start it up. 
261     if [ -z "$user" ]; then 
262        $cgroup $nice /bin/bash -c "$corelimit >/dev/null 2>&1 ; $*" 
263     else 
264        $cgroup $nice runuser -s /bin/bash $user -c "$corelimit >/dev/null 2>&1 ; $*" 
265     fi 
266  
267     [ "$?" -eq 0 ] && success $"$base startup" || failure $"$base startup" 
268 } 
269  
270 # A function to stop a program. 
271 killproc() { 
272     local RC killlevel= base pid pid_file= delay 
273  
274     RC=0; delay=3 
275     # Test syntax. 
276     if [ "$#" -eq 0 ]; then 
277         echo $"Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]" 
278         return 1 
279     fi 
280     if [ "$1" = "-p" ]; then 
281         pid_file=$2 
282         shift 2 
283     fi 
284     if [ "$1" = "-d" ]; then 
285         delay=$2 
286         shift 2 
287     fi 
288          
289  
290     # check for second arg to be kill level 
291     [ -n "${2:-}" ] && killlevel=$2 
292  
293         # Save basename. 
294         base=${1##*/} 
295  
296         # Find pid. 
297     __pids_var_run "$1" "$pid_file" 
298     RC=$? 
299     if [ -z "$pid" ]; then 
300         if [ -z "$pid_file" ]; then 
301             pid="$(__pids_pidof "$1")" 
302         else 
303             [ "$RC" = "4" ] && { failure $"$base shutdown" ; return $RC ;} 
304         fi 
305     fi 
306  
307         # Kill it. 
308         if [ -n "$pid" ] ; then 
309                 [ "$BOOTUP" = "verbose" -a -z "${LSB:-}" ] && echo -n "$base " 
310         if [ -z "$killlevel" ] ; then 
311                if checkpid $pid 2>&1; then 
312                # TERM first, then KILL if not dead 
313                kill -TERM $pid >/dev/null 2>&1 
314                usleep 100000 
315                if checkpid $pid && sleep 1 && 
316                   checkpid $pid && sleep $delay && 
317                   checkpid $pid ; then 
318                                 kill -KILL $pid >/dev/null 2>&1 
319                 usleep 100000 
320                fi 
321                 fi 
322             checkpid $pid 
323             RC=$? 
324             [ "$RC" -eq 0 ] && failure $"$base shutdown" || success $"$base shutdown" 
325             RC=$((! $RC)) 
326         # use specified level only 
327         else 
328                 if checkpid $pid; then 
329                         kill $killlevel $pid >/dev/null 2>&1 
330                 RC=$? 
331                 [ "$RC" -eq 0 ] && success $"$base $killlevel" || failure $"$base $killlevel" 
332             elif [ -n "${LSB:-}" ]; then 
333                 RC=7 # Program is not running 
334             fi 
335         fi 
336     else 
337         if [ -n "${LSB:-}" -a -n "$killlevel" ]; then 
338             RC=7 # Program is not running 
339         else 
340             failure $"$base shutdown" 
341             RC=0 
342         fi 
343     fi 
344  
345         # Remove pid file if any. 
346     if [ -z "$killlevel" ]; then 
347             rm -f "${pid_file:-/var/run/$base.pid}" 
348     fi 
349     return $RC 
350 } 
351  
352 # A function to find the pid of a program. Looks *only* at the pidfile 
353 pidfileofproc() { 
354     local pid 
355  
356     # Test syntax. 
357     if [ "$#" = 0 ] ; then 
358         echo $"Usage: pidfileofproc {program}" 
359         return 1 
360     fi 
361  
362     __pids_var_run "$1" 
363     [ -n "$pid" ] && echo $pid 
364     return 0 
365 } 
366  
367 # A function to find the pid of a program. 
368 pidofproc() { 
369     local RC pid pid_file= 
370  
371     # Test syntax. 
372     if [ "$#" = 0 ]; then 
373         echo $"Usage: pidofproc [-p pidfile] {program}" 
374         return 1 
375     fi 
376     if [ "$1" = "-p" ]; then 
377         pid_file=$2 
378         shift 2 
379     fi 
380     fail_code=3 # "Program is not running" 
381  
382     # First try "/var/run/*.pid" files 
383     __pids_var_run "$1" "$pid_file" 
384     RC=$? 
385     if [ -n "$pid" ]; then 
386         echo $pid 
387         return 0 
388     fi 
389  
390     [ -n "$pid_file" ] && return $RC 
391     __pids_pidof "$1" || return $RC 
392 } 
393  
394 status() { 
395     local base pid lock_file= pid_file= 
396  
397     # Test syntax. 
398     if [ "$#" = 0 ] ; then 
399         echo $"Usage: status [-p pidfile] {program}" 
400         return 1 
401     fi 
402     if [ "$1" = "-p" ]; then 
403         pid_file=$2 
404         shift 2 
405     fi 
406     if [ "$1" = "-l" ]; then 
407         lock_file=$2 
408         shift 2 
409     fi 
410     base=${1##*/} 
411  
412     # First try "pidof" 
413     __pids_var_run "$1" "$pid_file" 
414     RC=$? 
415     if [ -z "$pid_file" -a -z "$pid" ]; then 
416         pid="$(__pids_pidof "$1")" 
417     fi 
418     if [ -n "$pid" ]; then 
419             echo $"${base} (pid $pid) is running..." 
420             return 0 
421     fi 
422  
423     case "$RC" in 
424         0) 
425             echo $"${base} (pid $pid) is running..." 
426             return 0 
427             ;; 
428         1) 
429                     echo $"${base} dead but pid file exists" 
430                     return 1 
431             ;; 
432         4) 
433             echo $"${base} status unknown due to insufficient privileges." 
434             return 4 
435             ;; 
436     esac 
437     if [ -z "${lock_file}" ]; then 
438         lock_file=${base} 
439     fi 
440     # See if /var/lock/subsys/${lock_file} exists 
441     if [ -f /var/lock/subsys/${lock_file} ]; then 
442         echo $"${base} dead but subsys locked" 
443         return 2 
444     fi 
445     echo $"${base} is stopped" 
446     return 3 
447 } 
448  
449 echo_success() { 
450   [ "$BOOTUP" = "color" ] && $MOVE_TO_COL 
451   echo -n "[" 
452   [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS 
453   echo -n $"  OK  " 
454   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL 
455   echo -n "]" 
456   echo -ne "/r" 
457   return 0 
458 } 
459  
460 echo_failure() { 
461   [ "$BOOTUP" = "color" ] && $MOVE_TO_COL 
462   echo -n "[" 
463   [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE 
464   echo -n $"FAILED" 
465   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL 
466   echo -n "]" 
467   echo -ne "/r" 
468   return 1 
469 } 
470  
471 echo_passed() { 
472   [ "$BOOTUP" = "color" ] && $MOVE_TO_COL 
473   echo -n "[" 
474   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING 
475   echo -n $"PASSED" 
476   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL 
477   echo -n "]" 
478   echo -ne "/r" 
479   return 1 
480 } 
481  
482 echo_warning() { 
483   [ "$BOOTUP" = "color" ] && $MOVE_TO_COL 
484   echo -n "[" 
485   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING 
486   echo -n $"WARNING" 
487   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL 
488   echo -n "]" 
489   echo -ne "/r" 
490   return 1 
491 } 
492  
493 # Inform the graphical boot of our current state 
494 update_boot_stage() { 
495   if [ -x /bin/plymouth ]; then 
496       /bin/plymouth --update="$1" 
497   fi 
498   return 0 
499 } 
500  
501 # Log that something succeeded 
502 success() { 
503   [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_success 
504   return 0 
505 } 
506  
507 # Log that something failed 
508 failure() { 
509   local rc=$? 
510   [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_failure 
511   [ -x /bin/plymouth ] && /bin/plymouth --details 
512   return $rc 
513 } 
514  
515 # Log that something passed, but may have had errors. Useful for fsck 
516 passed() { 
517   local rc=$? 
518   [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_passed 
519   return $rc 
520 }   
521  
522 # Log a warning 
523 warning() { 
524   local rc=$? 
525   [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_warning 
526   return $rc 
527 }   
528  
529 # Run some action. Log its output. 
530 action() { 
531   local STRING rc 
532  
533   STRING=$1 
534   echo -n "$STRING " 
535   shift 
536   "$@" && success $"$STRING" || failure $"$STRING" 
537   rc=$? 
538   echo 
539   return $rc 
540 } 
541  
542 # returns OK if $1 contains $2 
543 strstr() { 
544   [ "${1#*$2*}" = "$1" ] && return 1 
545   return 0 
546 } 
547  
548 # Confirm whether we really want to run this service 
549 confirm() { 
550   [ -x /bin/plymouth ] && /bin/plymouth --hide-splash 
551   while : ; do  
552       echo -n $"Start service $1 (Y)es/(N)o/(C)ontinue? [Y] " 
553       read answer 
554       if strstr $"yY" "$answer" || [ "$answer" = "" ] ; then 
555          return 0 
556       elif strstr $"cC" "$answer" ; then 
557      rm -f /var/run/confirm 
558      [ -x /bin/plymouth ] && /bin/plymouth --show-splash 
559          return 2 
560       elif strstr $"nN" "$answer" ; then 
561          return 1 
562       fi 
563   done 
564 } 
565  
566 # resolve a device node to its major:minor numbers in decimal or hex 
567 get_numeric_dev() { 
568 ( 
569     fmt="%d:%d" 
570     if [ "$1" == "hex" ]; then 
571         fmt="%x:%x" 
572     fi 
573     ls -lH "$2" | awk '{ sub(/,/, "", $5); printf("'"$fmt"'", $5, $6); }' 
574 ) 2>/dev/null 
575 } 
576  
577 # Check whether file $1 is a backup or rpm-generated file and should be ignored 
578 is_ignored_file() { 
579     case "$1" in 
580     *~ | *.bak | *.orig | *.rpmnew | *.rpmorig | *.rpmsave) 
581         return 0 
582         ;; 
583     esac 
584     return 1 
585 } 
586  
587 # Evaluate shvar-style booleans 
588 is_true() { 
589     case "$1" in 
590     [tT] | [yY] | [yY][eE][sS] | [tT][rR][uU][eE]) 
591     return 0 
592     ;; 
593     esac 
594     return 1 
595 } 
596  
597 # Evaluate shvar-style booleans 
598 is_false() { 
599     case "$1" in 
600     [fF] | [nN] | [nN][oO] | [fF][aA][lL][sS][eE]) 
601     return 0 
602     ;; 
603     esac 
604     return 1 
605 } 
606  
607 # Apply sysctl settings, including files in /etc/sysctl.d 
608 apply_sysctl() { 
609     sysctl -e -p /etc/sysctl.conf >/dev/null 2>&1 
610     for file in /etc/sysctl.d/* ; do 
611         is_ignored_file "$file" && continue 
612         test -f "$file" && sysctl -e -p "$file" >/dev/null 2>&1 
613     done 
614 } 
615  
616 key_is_random() { 
617     [ "$1" = "/dev/urandom" -o "$1" = "/dev/hw_random" / 
618     -o "$1" = "/dev/random" ] 
619 } 
620  
621 find_crypto_mount_point() { 
622     local fs_spec fs_file fs_vfstype remaining_fields 
623     local fs 
624     while read fs_spec fs_file remaining_fields; do 
625     if [ "$fs_spec" = "/dev/mapper/$1" ]; then 
626         echo $fs_file 
627         break; 
628     fi 
629     done < /etc/fstab 
630 } 
631  
632 # Because of a chicken/egg problem, init_crypto must be run twice.  /var may be 
633 # encrypted but /var/lib/random-seed is needed to initialize swap. 
634 init_crypto() { 
635     local have_random dst src key opt mode owner params makeswap skip arg opt 
636     local param value rc ret mke2fs mdir prompt mount_point 
637  
638     ret=0 
639     have_random=$1 
640     while read dst src key opt; do 
641     [ -z "$dst" -o "${dst#/#}" != "$dst" ] && continue 
642         [ -b "/dev/mapper/$dst" ] && continue; 
643     if [ "$have_random" = 0 ] && key_is_random "$key"; then 
644         continue 
645     fi 
646     if [ -n "$key" -a "x$key" != "xnone" ]; then 
647         if test -e "$key" ; then 
648         owner=$(ls -l $key | (read a b owner rest; echo $owner)) 
649         if ! key_is_random "$key"; then 
650             mode=$(ls -l "$key" | cut -c 5-10) 
651             if [ "$mode" != "------" ]; then 
652                echo $"INSECURE MODE FOR $key" 
653             fi 
654         fi 
655         if [ "$owner" != root ]; then 
656             echo $"INSECURE OWNER FOR $key" 
657         fi 
658         else 
659         echo $"Key file for $dst not found, skipping" 
660         ret=1 
661         continue 
662         fi 
663     else 
664         key="" 
665     fi 
666     params="" 
667     makeswap="" 
668     mke2fs="" 
669     skip="" 
670     # Parse the src field for UUID= and convert to real device names 
671     if [ "${src%%=*}" == "UUID" ]; then 
672         src=$(/sbin/blkid -t "$src" -l -o device) 
673     elif [ "${src/^//dev//disk//by-uuid//}" != "$src" ]; then 
674         src=$(__readlink $src) 
675     fi 
676     # Is it a block device? 
677     [ -b "$src" ] || continue 
678     # Is it already a device mapper slave? (this is gross) 
679     devesc=${src##/dev/} 
680     devesc=${devesc/////!} 
681     for d in /sys/block/dm-*/slaves ; do 
682         [ -e $d/$devesc ] && continue 2 
683     done 
684     # Parse the options field, convert to cryptsetup parameters and 
685     # contruct the command line 
686     while [ -n "$opt" ]; do 
687         arg=${opt%%,*} 
688         opt=${opt##$arg} 
689         opt=${opt##,} 
690         param=${arg%%=*} 
691         value=${arg##$param=} 
692  
693         case "$param" in 
694         cipher) 
695         params="$params -c $value" 
696         if [ -z "$value" ]; then 
697             echo $"$dst: no value for cipher option, skipping" 
698             skip="yes" 
699         fi 
700         ;; 
701         size) 
702         params="$params -s $value" 
703         if [ -z "$value" ]; then 
704             echo $"$dst: no value for size option, skipping" 
705             skip="yes" 
706         fi 
707         ;; 
708         hash) 
709         params="$params -h $value" 
710         if [ -z "$value" ]; then 
711             echo $"$dst: no value for hash option, skipping" 
712             skip="yes" 
713         fi 
714         ;; 
715         verify) 
716             params="$params -y" 
717         ;; 
718         swap) 
719         makeswap=yes 
720         ;; 
721         tmp) 
722         mke2fs=yes 
723         esac 
724     done 
725     if [ "$skip" = "yes" ]; then 
726         ret=1 
727         continue 
728     fi 
729     if [ -z "$makeswap" ] && cryptsetup isLuks "$src" 2>/dev/null ; then 
730         if key_is_random "$key"; then 
731         echo $"$dst: LUKS requires non-random key, skipping" 
732         ret=1 
733         continue 
734         fi 
735         if [ -n "$params" ]; then 
736         echo "$dst: options are invalid for LUKS partitions," / 
737             "ignoring them" 
738         fi 
739         if [ -n "$key" ]; then 
740         /sbin/cryptsetup -d $key luksOpen "$src" "$dst" <&1 2>/dev/null && success || failure 
741         rc=$? 
742         else 
743         mount_point="$(find_crypto_mount_point $dst)" 
744         [ -n "$mount_point" ] || mount_point=${src##*/} 
745         prompt=$(printf $"%s is password protected" "$mount_point") 
746         plymouth ask-for-password --prompt "$prompt" --command="/sbin/cryptsetup luksOpen -T1 $src $dst" <&1 
747         rc=$? 
748         fi 
749     else 
750         [ -z "$key" ] && plymouth --hide-splash 
751         /sbin/cryptsetup $params ${key:+-d $key} create "$dst" "$src" <&1 2>/dev/null && success || failure 
752         rc=$? 
753         [ -z "$key" ] && plymouth --show-splash 
754     fi 
755     if [ $rc -ne 0 ]; then 
756         ret=1 
757         continue 
758     fi 
759     if [ -b "/dev/mapper/$dst" ]; then 
760         if [ "$makeswap" = "yes" ]; then 
761         mkswap "/dev/mapper/$dst" 2>/dev/null >/dev/null 
762         fi 
763         if [ "$mke2fs" = "yes" ]; then 
764         if mke2fs "/dev/mapper/$dst" 2>/dev/null >/dev/null / 
765             && mdir=$(mktemp -d /tmp/mountXXXXXX); then 
766             mount "/dev/mapper/$dst" "$mdir" && chmod 1777 "$mdir" 
767             umount "$mdir" 
768             rmdir "$mdir" 
769         fi 
770         fi 
771     fi 
772     done < /etc/crypttab 
773     return $ret 
774 } 
775  
776 # A sed expression to filter out the files that is_ignored_file recognizes 
777 __sed_discard_ignored_files='//(~/|/.bak/|/.orig/|/.rpmnew/|/.rpmorig/|/.rpmsave/)$/d'

View Code

1. portmap脚本

Linux 下Shell的学习3-优秀demo详解程序员

 1 #! /bin/sh 
 2 # 
 3 # portmap       Start/Stop RPC portmapper 
 4 # 
 5 # chkconfig: 345 13 87 
 6 # description: The portmapper manages RPC connections, which are used by / 
 7 #              protocols such as NFS and NIS. The portmap server must be / 
 8 #              running on machines which act as servers for protocols which / 
 9 #              make use of the RPC mechanism. 
10 # processname: portmap 
11  
12  
13 # This is an interactive program, we need the current locale 
14 [ -f /etc/profile.d/lang.sh ] && . /etc/profile.d/lang.sh 
15 # We can't Japanese on normal console at boot time, so force LANG=C. 
16 if [ "$LANG" = "ja" -o "$LANG" = "ja_JP.eucJP" ]; then 
17     if [ "$TERM" = "linux" ] ; then 
18         LANG=C 
19     fi 
20 fi 
21  
22 # Source function library. 
23 . /etc/init.d/functions 
24  
25 # Get config. 
26 if [ -f /etc/sysconfig/network ]; then 
27     . /etc/sysconfig/network 
28 else 
29     echo $"Networking not configured - exiting" 
30 ...skipping... 
31         stop 
32         start 
33         pmap_set < /var/run/portmap.state 
34         rm -f /var/run/portmap.state 
35 } 
36  
37 # See how we were called. 
38 case "$1" in 
39   start) 
40         start 
41         ;; 
42   stop) 
43         stop 
44         ;; 
45   status) 
46         status portmap 
47         ;; 
48   restart|reload) 
49         restart 
50         ;; 
51   condrestart) 
52         [ -f /var/lock/subsys/portmap ] && restart || : 
53         ;; 
54   *) 
55         echo $"Usage: $0 {start|stop|status|restart|reload|condrestart}" 
56         exit 1 
57 esac

View Code

2. rc.sysinit

Linux 下Shell的学习3-优秀demo详解程序员

  1 #!/bin/bash 
  2 # 
  3 # /etc/rc.d/rc.sysinit - run once at boot time 
  4 # 
  5 # Taken in part from Miquel van Smoorenburg's bcheckrc. 
  6 # 
  7  
  8 HOSTNAME=$(/bin/hostname) 
  9  
 10 set -m 
 11  
 12 if [ -f /etc/sysconfig/network ]; then 
 13     . /etc/sysconfig/network 
 14 fi 
 15 if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then 
 16     HOSTNAME=localhost 
 17 fi 
 18  
 19 if [ ! -e /proc/mounts ]; then 
 20     mount -n -t proc /proc /proc 
 21     mount -n -t sysfs /sys /sys >/dev/null 2>&1 
 22 fi 
 23 if [ ! -d /proc/bus/usb ]; then 
 24     modprobe usbcore >/dev/null 2>&1 && mount -n -t usbfs /proc/bus/usb /proc/bus/usb 
 25 else 
 26     mount -n -t usbfs /proc/bus/usb /proc/bus/usb 
 27 fi 
 28  
 29 #remount /dev/shm to set attributes from fstab #669700 
 30 mount -n -o remount /dev/shm >/dev/null 2>&1 
 31  
 32 . /etc/init.d/functions 
 33  
 34 PLYMOUTH= 
 35 [ -x /bin/plymouth ] && PLYMOUTH=yes 
 36  
 37 # Check SELinux status 
 38 SELINUX_STATE= 
 39 if [ -e "/selinux/enforce" ] && [ "$(cat /proc/self/attr/current)" != "kernel" ]; then 
 40     if [ -r "/selinux/enforce" ] ; then 
 41         SELINUX_STATE=$(cat "/selinux/enforce") 
 42     else 
 43         # assume enforcing if you can't read it 
 44         SELINUX_STATE=1 
 45     fi 
 46 fi 
 47  
 48 if [ -n "$SELINUX_STATE" -a -x /sbin/restorecon ] && __fgrep " /dev " /proc/mounts >/dev/null 2>&1 ; then 
 49     /sbin/restorecon -R -F /dev 2>/dev/null 
 50 fi 
 51  
 52 disable_selinux() { 
 53     echo $"*** Warning -- SELinux is active" 
 54     echo $"*** Disabling security enforcement for system recovery." 
 55     echo $"*** Run 'setenforce 1' to reenable." 
 56     echo "0" > "/selinux/enforce" 
 57 } 
 58  
 59 relabel_selinux() { 
 60     # if /sbin/init is not labeled correctly this process is running in the 
 61     # wrong context, so a reboot will be required after relabel 
 62     AUTORELABEL= 
 63     . /etc/selinux/config 
 64     echo "0" > /selinux/enforce 
 65     [ -n "$PLYMOUTH" ] && plymouth --hide-splash 
 66  
 67     if [ "$AUTORELABEL" = "0" ]; then 
 68     echo 
 69     echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required. " 
 70     echo $"*** /etc/selinux/config indicates you want to manually fix labeling" 
 71     echo $"*** problems. Dropping you to a shell; the system will reboot" 
 72     echo $"*** when you leave the shell." 
 73     start rcS-emergency 
 74  
 75     else 
 76     echo 
 77     echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required." 
 78     echo $"*** Relabeling could take a very long time, depending on file" 
 79     echo $"*** system size and speed of hard drives." 
 80  
 81     /sbin/fixfiles -F restore > /dev/null 2>&1 
 82     fi 
 83     rm -f  /.autorelabel 
 84     echo $"Unmounting file systems" 
 85     umount -a 
 86     mount -n -o remount,ro / 
 87     echo $"Automatic reboot in progress." 
 88     reboot -f 
 89 } 
 90  
 91 # Print a text banner. 
 92 echo -en $"/t/tWelcome to " 
 93 read -r system_release < /etc/system-release 
 94 if [[ "$system_release" == *"Red Hat"* ]]; then 
 95  [ "$BOOTUP" = "color" ] && echo -en "//033[0;31m" 
 96  echo -en "Red Hat" 
 97  [ "$BOOTUP" = "color" ] && echo -en "//033[0;39m" 
 98  PRODUCT=$(sed "s/Red Hat /(.*/) release.*//1/" /etc/system-release) 
 99  echo " $PRODUCT" 
100 elif [[ "$system_release" == *Fedora* ]]; then 
101  [ "$BOOTUP" = "color" ] && echo -en "//033[0;34m" 
102  echo -en "Fedora" 
103  [ "$BOOTUP" = "color" ] && echo -en "//033[0;39m" 
104  PRODUCT=$(sed "s/Fedora /(.*/) /?release.*//1/" /etc/system-release) 
105  echo " $PRODUCT" 
106 elif [[ "$system_release" =~ "CentOS" ]]; then 
107  [ "$BOOTUP" = "color" ] && echo -en "//033[0;36m" 
108  echo -en "CentOS" 
109  [ "$BOOTUP" = "color" ] && echo -en "//033[0;39m" 
110  PRODUCT=$(sed "s/CentOS /(.*/) /?release.*//1/" /etc/system-release) 
111  echo " $PRODUCT" 
112 else 
113  PRODUCT=$(sed "s/ release.*//g" /etc/system-release) 
114  echo "$PRODUCT" 
115 fi 
116  
117 # Only read this once. 
118 cmdline=$(cat /proc/cmdline) 
119  
120 # Initialize hardware 
121 if [ -f /proc/sys/kernel/modprobe ]; then 
122    if ! strstr "$cmdline" nomodules && [ -f /proc/modules ] ; then 
123        sysctl -w kernel.modprobe="/sbin/modprobe" >/dev/null 2>&1 
124    else 
125        # We used to set this to NULL, but that causes 'failed to exec' messages" 
126        sysctl -w kernel.modprobe="/bin/true" >/dev/null 2>&1 
127    fi 
128 fi 
129  
130 touch /dev/.in_sysinit >/dev/null 2>&1 
131  
132 # Set default affinity 
133 if [ -x /bin/taskset ]; then 
134    if strstr "$cmdline" default_affinity= ; then 
135      for arg in $cmdline ; do 
136          if [ "${arg##default_affinity=}" != "${arg}" ]; then 
137              /bin/taskset -p ${arg##default_affinity=} 1 
138          fi 
139      done 
140    fi 
141 fi 
142  
143 nashpid=$(pidof nash 2>/dev/null) 
144 [ -n "$nashpid" ] && kill $nashpid >/dev/null 2>&1 
145 unset nashpid 
146 /sbin/start_udev 
147  
148 # Load other user-defined modules 
149 for file in /etc/sysconfig/modules/*.modules ; do 
150   [ -x $file ] && $file 
151 done 
152  
153 # Load modules (for backward compatibility with VARs) 
154 if [ -f /etc/rc.modules ]; then 
155     /etc/rc.modules 
156 fi 
157  
158 mount -n /dev/pts >/dev/null 2>&1 
159 [ -n "$SELINUX_STATE" ] && restorecon -F /dev/pts >/dev/null 2>&1 
160  
161 # Configure kernel parameters 
162 update_boot_stage RCkernelparam 
163 apply_sysctl 
164  
165 # Set the hostname. 
166 update_boot_stage RChostname 
167 action $"Setting hostname ${HOSTNAME}: " hostname ${HOSTNAME} 
168 [ -n "${NISDOMAIN}" ] && domainname ${NISDOMAIN} 
169  
170 # Sync waiting for storage. 
171 { rmmod scsi_wait_scan ; modprobe scsi_wait_scan ; rmmod scsi_wait_scan ; } >/dev/null 2>&1 
172  
173 # Device mapper & related initialization 
174 if ! __fgrep "device-mapper" /proc/devices >/dev/null 2>&1 ; then 
175        modprobe dm-mod >/dev/null 2>&1 
176 fi 
177  
178 if [ -f /etc/crypttab ]; then 
179     init_crypto 0 
180 fi 
181  
182 if ! strstr "$cmdline" nompath && [ -f /etc/multipath.conf -a / 
183         -x /sbin/multipath ]; then 
184     modprobe dm-multipath > /dev/null 2>&1 
185     /sbin/multipath -v 0 
186     if [ -x /sbin/kpartx ]; then 
187         /sbin/dmsetup ls --target multipath --exec "/sbin/kpartx -a -p p" >/dev/null 
188     fi 
189 fi 
190  
191 if ! strstr "$cmdline" nodmraid && [ -x /sbin/dmraid ]; then 
192     modprobe dm-mirror >/dev/null 2>&1 
193     dmraidsets=$(LC_ALL=C /sbin/dmraid -s -c -i) 
194     if [ "$?" = "0" ]; then 
195         for dmname in $dmraidsets; do 
196             if [[ "$dmname" == isw_* ]] && / 
197                ! strstr "$cmdline" noiswmd; then 
198                 continue 
199             fi 
200             /sbin/dmraid -ay -i --rm_partitions -p "$dmname" >/dev/null 2>&1 
201             /sbin/kpartx -a -p p "/dev/mapper/$dmname" 
202         done 
203     fi 
204 fi 
205  
206 # Start any MD RAID arrays that haven't been started yet 
207 [ -r /proc/mdstat -a -r /dev/md/md-device-map ] && /sbin/mdadm -IRs 
208  
209 if [ -x /sbin/lvm ]; then 
210     action $"Setting up Logical Volume Management:" /sbin/lvm vgchange -a ay --sysinit 
211 fi 
212  
213 if [ -f /etc/crypttab ]; then 
214     init_crypto 0 
215 fi 
216  
217 if [ -f /fastboot ] || strstr "$cmdline" fastboot ; then 
218     fastboot=yes 
219 fi 
220  
221 if [ -f /fsckoptions ]; then 
222     fsckoptions=$(cat /fsckoptions) 
223 fi 
224  
225 if [ -f /forcefsck ] || strstr "$cmdline" forcefsck ; then 
226     fsckoptions="-f $fsckoptions" 
227 elif [ -f /.autofsck ]; then 
228     [ -f /etc/sysconfig/autofsck ] && . /etc/sysconfig/autofsck 
229     if [ "$AUTOFSCK_DEF_CHECK" = "yes" ]; then 
230         AUTOFSCK_OPT="$AUTOFSCK_OPT -f" 
231     fi 
232     if [ -n "$AUTOFSCK_SINGLEUSER" ]; then 
233         [ -n "$PLYMOUTH" ] && plymouth --hide-splash 
234         echo 
235         echo $"*** Warning -- the system did not shut down cleanly. " 
236         echo $"*** Dropping you to a shell; the system will continue" 
237         echo $"*** when you leave the shell." 
238         [ -n "$SELINUX_STATE" ] && echo "0" > /selinux/enforce 
239         start rcS-emergency 
240         [ -n "$SELINUX_STATE" ] && echo "1" > /selinux/enforce 
241         [ -n "$PLYMOUTH" ] && plymouth --show-splash 
242     fi 
243     fsckoptions="$AUTOFSCK_OPT $fsckoptions" 
244 fi 
245  
246 if [ "$BOOTUP" = "color" ]; then 
247     fsckoptions="-C $fsckoptions" 
248 else 
249     fsckoptions="-V $fsckoptions" 
250 fi 
251  
252 READONLY= 
253 if [ -f /etc/sysconfig/readonly-root ]; then 
254     . /etc/sysconfig/readonly-root 
255 fi 
256 if strstr "$cmdline" readonlyroot ; then 
257     READONLY=yes 
258     [ -z "$RW_MOUNT" ] && RW_MOUNT=/var/lib/stateless/writable 
259     [ -z "$STATE_MOUNT" ] && STATE_MOUNT=/var/lib/stateless/state 
260 fi 
261 if strstr "$cmdline" noreadonlyroot ; then 
262     READONLY=no 
263 fi 
264  
265 if [ "$READONLY" = "yes" -o "$TEMPORARY_STATE" = "yes" ]; then 
266  
267     mount_empty() { 
268         if [ -e "$1" ]; then 
269             echo "$1" | cpio -p -vd "$RW_MOUNT" &>/dev/null 
270             mount -n --bind "$RW_MOUNT$1" "$1" 
271         fi 
272     } 
273  
274     mount_dirs() { 
275         if [ -e "$1" ]; then 
276             mkdir -p "$RW_MOUNT$1" 
277             find "$1" -type d -print0 | cpio -p -0vd "$RW_MOUNT" &>/dev/null 
278             mount -n --bind "$RW_MOUNT$1" "$1" 
279         fi 
280     } 
281  
282     mount_files() { 
283         if [ -e "$1" ]; then 
284             cp -a --parents "$1" "$RW_MOUNT" 
285             mount -n --bind "$RW_MOUNT$1" "$1" 
286         fi 
287     } 
288  
289     # Common mount options for scratch space regardless of 
290     # type of backing store 
291     mountopts= 
292  
293     # Scan partitions for local scratch storage 
294     rw_mount_dev=$(blkid -t LABEL="$RW_LABEL" -l -o device) 
295  
296     # First try to mount scratch storage from /etc/fstab, then any 
297     # partition with the proper label.  If either succeeds, be sure 
298     # to wipe the scratch storage clean.  If both fail, then mount 
299     # scratch storage via tmpfs. 
300     if mount $mountopts "$RW_MOUNT" > /dev/null 2>&1 ; then 
301         rm -rf "$RW_MOUNT" > /dev/null 2>&1 
302     elif [ x$rw_mount_dev != x ] && mount $rw_mount_dev $mountopts "$RW_MOUNT" > /dev/null 2>&1; then 
303         rm -rf "$RW_MOUNT"  > /dev/null 2>&1 
304     else 
305         mount -n -t tmpfs $RW_OPTIONS $mountopts none "$RW_MOUNT" 
306     fi 
307  
308     for file in /etc/rwtab /etc/rwtab.d/* /dev/.initramfs/rwtab ; do 
309         is_ignored_file "$file" && continue 
310     [ -f $file ] && cat $file | while read type path ; do 
311             case "$type" in 
312                 empty) 
313                     mount_empty $path 
314                     ;; 
315                 files) 
316                     mount_files $path 
317                     ;; 
318                 dirs) 
319                     mount_dirs $path 
320                     ;; 
321                 *) 
322                     ;; 
323             esac 
324             [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" 
325         done 
326     done 
327  
328     # Use any state passed by initramfs 
329     [ -d /dev/.initramfs/state ] && cp -a /dev/.initramfs/state/* $RW_MOUNT 
330  
331     # In theory there should be no more than one network interface active 
332     # this early in the boot process -- the one we're booting from. 
333     # Use the network address to set the hostname of the client.  This 
334     # must be done even if we have local storage. 
335     ipaddr= 
336     if [ "$HOSTNAME" = "localhost" -o "$HOSTNAME" = "localhost.localdomain" ]; then 
337         ipaddr=$(ip addr show to 0.0.0.0/0 scope global | awk '/[[:space:]]inet / { print gensub("/.*","","g",$2) }') 
338         for ip in $ipaddr ; do 
339             HOSTNAME= 
340             eval $(ipcalc -h $ip 2>/dev/null) 
341             [ -n "$HOSTNAME" ] && { hostname ${HOSTNAME} ; break; } 
342         done 
343     fi 
344      
345     # Clients with read-only root filesystems may be provided with a 
346     # place where they can place minimal amounts of persistent 
347     # state.  SSH keys or puppet certificates for example. 
348     # 
349     # Ideally we'll use puppet to manage the state directory and to 
350     # create the bind mounts.  However, until that's all ready this 
351     # is sufficient to build a working system. 
352  
353     # First try to mount persistent data from /etc/fstab, then any 
354     # partition with the proper label, then fallback to NFS 
355     state_mount_dev=$(blkid -t LABEL="$STATE_LABEL" -l -o device) 
356     if mount $mountopts $STATE_OPTIONS "$STATE_MOUNT" > /dev/null 2>&1 ; then 
357         /bin/true 
358     elif [ x$state_mount_dev != x ] && mount $state_mount_dev $mountopts "$STATE_MOUNT" > /dev/null 2>&1;  then 
359         /bin/true 
360     elif [ ! -z "$CLIENTSTATE" ]; then 
361         # No local storage was found.  Make a final attempt to find 
362         # state on an NFS server. 
363  
364         mount -t nfs $CLIENTSTATE/$HOSTNAME $STATE_MOUNT -o rw,nolock 
365     fi 
366  
367     if [ -w "$STATE_MOUNT" ]; then 
368  
369         mount_state() { 
370             if [ -e "$1" ]; then 
371                 [ ! -e "$STATE_MOUNT$1" ] && cp -a --parents "$1" "$STATE_MOUNT" 
372                 mount -n --bind "$STATE_MOUNT$1" "$1" 
373             fi 
374         } 
375  
376         for file in /etc/statetab /etc/statetab.d/* ; do 
377             is_ignored_file "$file" && continue 
378             [ ! -f "$file" ] && continue 
379  
380             if [ -f "$STATE_MOUNT/$file" ] ; then 
381                 mount -n --bind "$STATE_MOUNT/$file" "$file" 
382             fi 
383  
384             for path in $(grep -v "^#" "$file" 2>/dev/null); do 
385                 mount_state "$path" 
386                 [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" 
387             done 
388         done 
389  
390         if [ -f "$STATE_MOUNT/files" ] ; then 
391             for path in $(grep -v "^#" "$STATE_MOUNT/files" 2>/dev/null); do 
392                 mount_state "$path" 
393                 [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" 
394             done 
395         fi 
396     fi 
397 fi 
398  
399 if [[ " $fsckoptions" != *" -y"* ]]; then 
400     fsckoptions="-a $fsckoptions" 
401 fi 
402  
403 _RUN_QUOTACHECK=0 
404 if [ -f /forcequotacheck ] || strstr "$cmdline" forcequotacheck ; then 
405     _RUN_QUOTACHECK=1 
406 fi 
407 if [ -z "$fastboot" -a "$READONLY" != "yes" ]; then 
408  
409         STRING=$"Checking filesystems" 
410     echo $STRING 
411     fsck -T -t noopts=_netdev -A $fsckoptions 
412     rc=$? 
413      
414     if [ "$rc" -eq "0" ]; then 
415         success "$STRING" 
416         echo 
417     elif [ "$rc" -eq "1" ]; then 
418             passed "$STRING" 
419         echo 
420     elif [ "$rc" -eq "2" -o "$rc" -eq "3" ]; then 
421         echo $"Unmounting file systems" 
422         umount -a 
423         mount -n -o remount,ro / 
424         echo $"Automatic reboot in progress." 
425         reboot -f 
426         fi 
427      
428         # A return of 4 or higher means there were serious problems. 
429     if [ $rc -gt 1 ]; then 
430         [ -n "$PLYMOUTH" ] && plymouth --hide-splash 
431  
432         failure "$STRING" 
433         echo 
434         echo 
435         echo $"*** An error occurred during the file system check." 
436         echo $"*** Dropping you to a shell; the system will reboot" 
437         echo $"*** when you leave the shell." 
438  
439                 str=$"(Repair filesystem)" 
440         PS1="$str /# # "; export PS1 
441         [ "$SELINUX_STATE" = "1" ] && disable_selinux 
442         start rcS-emergency 
443  
444         echo $"Unmounting file systems" 
445         umount -a 
446         mount -n -o remount,ro / 
447         echo $"Automatic reboot in progress." 
448         reboot -f 
449     elif [ "$rc" -eq "1" ]; then 
450         _RUN_QUOTACHECK=1 
451     fi 
452 fi 
453  
454 remount_needed() { 
455   local state oldifs 
456   [ "$READONLY" = "yes" ] && return 1 
457   state=$(LC_ALL=C awk '/ // / && ($3 !~ /rootfs/) { print $4 }' /proc/mounts) 
458   oldifs=$IFS 
459   IFS="," 
460   for opt in $state ; do 
461     if [ "$opt" = "rw" ]; then 
462         IFS=$oldifs 
463         return 1 
464     fi 
465   done 
466   IFS=$oldifs 
467   return 0 
468 } 
469  
470 # Remount the root filesystem read-write. 
471 update_boot_stage RCmountfs 
472 if remount_needed ; then 
473   action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw / 
474 fi 
475  
476 # Clean up SELinux labels 
477 if [ -n "$SELINUX_STATE" ]; then 
478    restorecon /etc/mtab /etc/ld.so.cache /etc/blkid/blkid.tab /etc/resolv.conf >/dev/null 2>&1 
479 fi 
480  
481 # If relabeling, relabel mount points. 
482 if [ -n "$SELINUX_STATE" -a "$READONLY" != "yes" ]; then 
483     if [ -f /.autorelabel ] || strstr "$cmdline" autorelabel ; then 
484     restorecon $(awk '!/^#/ && $4 !~ /noauto/ && $2 ~ /^/// { print $2 }' /etc/fstab) >/dev/null 2>&1 
485     fi 
486 fi 
487  
488 if [ "$READONLY" != "yes" ] ; then 
489     # Clear mtab 
490     (> /etc/mtab) &> /dev/null 
491  
492     # Remove stale backups 
493     rm -f /etc/mtab~ /etc/mtab~~ 
494  
495     # Enter mounted filesystems into /etc/mtab 
496     mount -f / 
497     mount -f /proc >/dev/null 2>&1 
498     mount -f /sys >/dev/null 2>&1 
499     mount -f /dev/pts >/dev/null 2>&1 
500     mount -f /dev/shm >/dev/null 2>&1 
501     mount -f /proc/bus/usb >/dev/null 2>&1 
502 fi 
503  
504 # Mount all other filesystems (except for NFS and /proc, which is already 
505 # mounted). Contrary to standard usage, 
506 # filesystems are NOT unmounted in single user mode. 
507 # The 'no' applies to all listed filesystem types. See mount(8). 
508 if [ "$READONLY" != "yes" ] ; then 
509     action $"Mounting local filesystems: " mount -a -t nonfs,nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev 
510 else 
511     action $"Mounting local filesystems: " mount -a -n -t nonfs,nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev 
512 fi 
513  
514 # Update quotas if necessary 
515 if [ X"$_RUN_QUOTACHECK" = X1 -a -x /sbin/quotacheck ]; then 
516     action $"Checking local filesystem quotas: " /sbin/quotacheck -anug 
517 fi 
518  
519 if [ -x /sbin/quotaon ]; then 
520     action $"Enabling local filesystem quotas: " /sbin/quotaon -aug 
521 fi 
522  
523 # Check to see if a full relabel is needed 
524 if [ -n "$SELINUX_STATE" -a "$READONLY" != "yes" ]; then 
525     if [ -f /.autorelabel ] || strstr "$cmdline" autorelabel ; then 
526     relabel_selinux 
527     fi 
528 else 
529     if [ -d /etc/selinux -a "$READONLY" != "yes" ]; then 
530         [ -f /.autorelabel ] || touch /.autorelabel 
531     fi 
532 fi 
533  
534 # Initialize pseudo-random number generator 
535 if [ -f "/var/lib/random-seed" ]; then 
536     cat /var/lib/random-seed > /dev/urandom 
537 else 
538     [ "$READONLY" != "yes" ] && touch /var/lib/random-seed 
539 fi 
540 if [ "$READONLY" != "yes" ]; then 
541     chmod 600 /var/lib/random-seed 
542     dd if=/dev/urandom of=/var/lib/random-seed count=1 bs=512 2>/dev/null 
543 fi 
544  
545 if [ -f /etc/crypttab ]; then 
546     init_crypto 1 
547 fi 
548  
549 # Configure machine if necessary. 
550 if [ -f /.unconfigured ]; then 
551  
552     if [ -x /bin/plymouth ]; then 
553         /bin/plymouth quit 
554     fi 
555  
556     if [ -x /usr/bin/system-config-keyboard ]; then 
557     /usr/bin/system-config-keyboard 
558     fi 
559     if [ -x /usr/bin/passwd ]; then 
560         /usr/bin/passwd root 
561     fi 
562     if [ -x /usr/sbin/system-config-network-tui ]; then 
563     /usr/sbin/system-config-network-tui 
564     fi 
565     if [ -x /usr/sbin/timeconfig ]; then 
566     /usr/sbin/timeconfig 
567     fi 
568     if [ -x /usr/sbin/authconfig-tui ]; then 
569     /usr/sbin/authconfig-tui --nostart 
570     fi 
571     if [ -x /usr/sbin/ntsysv ]; then 
572     /usr/sbin/ntsysv --level 35 
573     fi 
574  
575     # Reread in network configuration data. 
576     if [ -f /etc/sysconfig/network ]; then 
577     . /etc/sysconfig/network 
578  
579     # Reset the hostname. 
580     action $"Resetting hostname ${HOSTNAME}: " hostname ${HOSTNAME} 
581     fi 
582  
583     rm -f /.unconfigured 
584 fi 
585  
586 # Clean out /. 
587 rm -f /fastboot /fsckoptions /forcefsck /.autofsck /forcequotacheck /halt / 
588     /poweroff /.suspended &> /dev/null 
589  
590 # Do we need (w|u)tmpx files? We don't set them up, but the sysadmin might... 
591 _NEED_XFILES= 
592 [ -f /var/run/utmpx -o -f /var/log/wtmpx ] && _NEED_XFILES=1 
593  
594 # Clean up /var. 
595 rm -rf /var/lock/cvs/* /var/run/screen/* 
596 find /var/lock /var/run ! -type d -exec rm -f {} /; 
597 rm -f /var/lib/rpm/__db* &> /dev/null 
598 rm -f /var/gdm/.gdmfifo &> /dev/null 
599  
600 [ "$PROMPT" != no ] && plymouth watch-keystroke --command "touch /var/run/confirm" --keys=Ii & 
601  
602 # Clean up utmp/wtmp 
603 > /var/run/utmp 
604 touch /var/log/wtmp 
605 chgrp utmp /var/run/utmp /var/log/wtmp 
606 chmod 0664 /var/run/utmp /var/log/wtmp 
607 if [ -n "$_NEED_XFILES" ]; then 
608   > /var/run/utmpx 
609   touch /var/log/wtmpx 
610   chgrp utmp /var/run/utmpx /var/log/wtmpx 
611   chmod 0664 /var/run/utmpx /var/log/wtmpx 
612 fi 
613 [ -n "$SELINUX_STATE" ] && restorecon /var/run/utmp* /var/log/wtmp* >/dev/null 2>&1 
614  
615 # Clean up various /tmp bits 
616 [ -n "$SELINUX_STATE" ] && restorecon /tmp 
617 rm -f /tmp/.X*-lock /tmp/.lock.* /tmp/.gdm_socket /tmp/.s.PGSQL.* 
618 rm -rf /tmp/.X*-unix /tmp/.ICE-unix /tmp/.font-unix /tmp/hsperfdata_* / 
619        /tmp/kde-* /tmp/ksocket-* /tmp/mc-* /tmp/mcop-* /tmp/orbit-*  / 
620        /tmp/scrollkeeper-*  /tmp/ssh-* / 
621        /dev/.in_sysinit 
622  
623 # Make ICE directory 
624 mkdir -m 1777 -p /tmp/.ICE-unix >/dev/null 2>&1 
625 chown root:root /tmp/.ICE-unix 
626 [ -n "$SELINUX_STATE" ] && restorecon /tmp/.ICE-unix >/dev/null 2>&1 
627  
628 # Start up swapping. 
629 update_boot_stage RCswap 
630 action $"Enabling /etc/fstab swaps: " swapon -a -e 
631 if [ "$AUTOSWAP" = "yes" ]; then 
632     curswap=$(awk '/^//dev/ { print $1 }' /proc/swaps | while read x; do get_numeric_dev dec $x ; echo -n " "; done) 
633     swappartitions=$(blkid -t TYPE=swap -o device) 
634     if [ x"$swappartitions" != x ]; then 
635         for partition in $swappartitions ; do 
636             [ ! -e $partition ] && continue 
637             majmin=$(get_numeric_dev dec $partition) 
638             echo $curswap | grep -qw "$majmin" || action $"Enabling local swap partitions: " swapon $partition 
639         done 
640     fi 
641 fi 
642  
643 # Set up binfmt_misc 
644 /bin/mount -t binfmt_misc none /proc/sys/fs/binfmt_misc > /dev/null 2>&1 
645  
646 # Boot time profiles. Yes, this should be somewhere else. 
647 if [ -x /usr/sbin/system-config-network-cmd ]; then 
648   if strstr "$cmdline" netprofile= ; then 
649     for arg in $cmdline ; do 
650         if [ "${arg##netprofile=}" != "${arg}" ]; then 
651         /usr/sbin/system-config-network-cmd --profile ${arg##netprofile=} 
652         fi 
653     done 
654   fi 
655 fi 
656  
657 # Now that we have all of our basic modules loaded and the kernel going, 
658 # let's dump the syslog ring somewhere so we can find it later 
659 [ -f /var/log/dmesg ] && mv -f /var/log/dmesg /var/log/dmesg.old 
660 dmesg -s 131072 > /var/log/dmesg 
661  
662 # create the crash indicator flag to warn on crashes, offer fsck with timeout 
663 touch /.autofsck &> /dev/null 
664  
665 [ "$PROMPT" != no ] && plymouth --ignore-keystroke=Ii 
666 if strstr "$cmdline" confirm ; then 
667     touch /var/run/confirm 
668 fi 
669  
670 # Let rhgb know that we're leaving rc.sysinit 
671 if [ -x /bin/plymouth ]; then 
672     /bin/plymouth --sysinit 
673 fi

View Code

  

 FLT的DEMO

0. 一键式[未完成版本]

Linux 下Shell的学习3-优秀demo详解程序员

  1 #set env 
  2 export PATH=$PATH:/bin:/sbin:/usr/sbin 
  3 export LANG='us' 
  4  
  5 #Root allowed 
  6 if [ `whoami` != 'root' ];then 
  7   echo "Please run this script with root "  
  8   exit 1 
  9 fi 
 10  
 11 #define cmd var 
 12 SERVICE=`which service` 
 13 CHKCONFIG= `which chkconfig` 
 14  
 15 #import libiary 
 16 . /etc/init.d/functions 
 17  
 18 #Config Yum Config 
 19 function yum(){ 
 20   echo "Config Yum Centos-Base.repo" 
 21   cd /etc/yum.repos.d/ 
 22   cp rhel-source.repo rhel-source.repo.$(date +%F) 
 23   ping www.baidu.com 
 24   [ $? -eq 0 ] && echo $"Networking not configured" && exit 1 
 25   wget --quiet http://mirrors.163.com/.help/CentOS6-Base-163.repo 
 26   sed -i 's/$releasever/6/g' CentOS6-Base-163.repo  
 27   chmod 644 CentOS6-Base-163.repo 
 28   chown root.root CentOS6-Base-163.repo 
 29 } 
 30  
 31 #Install Init Package 
 32 function installTool(){ 
 33   echo "sysstat ntp net-snmp lrzsz rsync" 
 34   yum install sysstat ntp net-snmp lrzsz rsync 2>&/dev/null 
 35 } 
 36  
 37 #Chinese GB18030 
 38 function initI18n(){ 
 39   echo "#set LANG="zh_cn.gb18030"" 
 40   cp /etc/sysconfig/i18n /etc/sysconfig/i18n_`date +%F` 
 41   sed -i 's/LANG="en_US.UTF-8"/LANG="zh_CN.GB18030"/g' /etc/sysconfig/i18n 
 42   grep LANG /etc/sysconfig/i18n 
 43   sleep 1 
 44 } 
 45  
 46 #close selinux and iptables 
 47 initFirewall(){ 
 48   echo "#close selinux and firewall" 
 49   cp  /etc/selinux/config   /etc/selinux/config_`date +%F` 
 50   /etc/init.d/iptables stop 
 51   sed -i 's/SELINUX=enable/SELINUX=disable/g'  /etc/selinux/config  
 52   setenforce  0 
 53   /etc/init.d/iptables status 
 54   grep SELINUX=disable  /etc/selinux/config  
 55   echo "Close selinux        Ok " 
 56   echo "Close firewall       Ok " 
 57   sleep 1 
 58  } 
 59  
 60 #Init Auto Startup Service 
 61 function initService(){ 
 62   echo "Close Nonuseful service..." 
 63   exprt LANG=us 
 64   chkconfig |grep 3:on | awk '{print $1}' | grep -Ev "sshd|network|crond|sysstat|rsyslog" | xargs -I{} chkconfig {} off 
 65   echo "Service sshd|network|crond|sysstat|rsyslog is Running...." 
 66   sleep 1 
 67 } 
 68  
 69 #Init ssh 
 70 function ssh(){ 
 71   echo "config sshConfig ...." 
 72   cp /etc/ssh/sshd_config /etc/ssh/sshd_config_`date +%F` 
 73   sed -i 's#GSSAPIAuthentication yes#GSSAPIAuthentication no#g' /etc/ssh/sshd_config 
 74   sed -i 's#PermitRootLogin no#PermitRootLogin no#g' /etc/ssh/sshd_config 
 75   sed -i 's%#Port 22%Port 11544%g' /etc/ssh/sshd_config 
 76 } 
 77  
 78 #AddUser 
 79 function addUser(){ 
 80   echo "add User for Linux System..." 
 81   cp /etc/sudoers /etc/sudoers_`date +%F` 
 82   saUserArr={omc webserver webserverpt} 
 83   groupadd -g 888 sa 
 84   for((i=0;i<${#saUserArr[@]};i++)) 
 85   do 
 86     useradd -g sa -u88${i} ${saUserArr[$i]} 
 87     echo "${saUserArr[$i]}123"|passwd ${saUserArr[$i]} --stdin 
 88     # add sudoers  
 89     # ... 
 90     # /usr/sbin/visudo -c 
 91     # [ $? -ne 0 ] && /bin/cp /etc/sudoers.`date +%F` /etc/sudoers && echo $"Sudoers not configured --exit" && exit 1 
 92     # action $"useradd is ok "   /bin/true 
 93   done 
 94 } 
 95  
 96 #Sync Time 
 97 function sysncTime(){ 
 98   if [ `grep pool.ntp.ort /var/spool/cron/root|grep -v grep |wc -l` -lt 1 ];then 
 99     echo "*/5 * * * * /usr/sbin/ntpdate cn.pool.ntp.org 2&>/dev/null"  >> /var/spool/cron/root 
100   fi 
101 } 
102  
103 #adjuct File 
104 function openFile(){ 
105   echo "adjust the max opened files are 65535" 
106   cp /etc/security/limits.conf /etc/security/limits.conf_`date +%F` 
107   echo '  *           -      nofile   65535' >> /etc/security/limits.conf 
108   ulimit -SHn 65535  
109   echo "adjust the max opened files are 65535 is ok " 
110   sleep 1 
111 } 
112  
113 #adjust kernal 
114 function optimizationKernal(){ 
115   echo "optimizationKernal..." 
116   cp /etc/sysctl.conf  /etc/sysctl.conf_`date +%F` 
117   cat >> /etc/sysctl.conf<<EOF 
118   net.ipv4.tcp_timestamps=0 
119 EOF 
120   /sbin/sysctl -p && action "optimizationKernal is ok " /bin/true || actio "optimizationKernal is wrong" /bin/false 
121  
122 } 
123  
124 function safe(){ 
125   echo "" 
126 }

View Code

1. 清除日志 

Linux 下Shell的学习3-优秀demo详解程序员

 1 #!/bin/sh 
 2 #clear log file 
 3 LOG_DIR=/var/log 
 4 ROOT_UID=0 
 5 #ROOT用户执行 
 6 if [ "$UID" -ne ROOT_UID ] 
 7    then 
 8    echo 'Must be root to run this script' 
 9    exit 1 
10 fi 
11 cd $LOG_DIR ||{ 
12    echo "Cannot change to $LOG_DIR " >/dev/null 
13    exit 1 
14 } 
15 cat /dev/null > messages 
16 echo "Logs cleaned up" 
17 exit 0

View Code

2. 利用shell数组函数检查多个url地址的案例

Linux 下Shell的学习3-优秀demo详解程序员

#!/bin/sh 
#use array by 20170911 
 
#use function 
. /etc/init.d/functions  
 
array=( 
  www.baidu.com 
  www.hao123.com 
  www.51cto.com 
  ) 
 
function wait(){ 
  echo -n "3mins to start the script..." 
  for((i=0;i<${#array[*]};i++)) 
  do 
    echo -n '.'; 
    sleep 1 
  done 
} 
 
function check_url(){ 
  for ((i=0;i<${#array[*]};i++)) 
  do 
     judge=(`curl -I ${array[$i]} -s |head -1`) 
     #echo "${array[$i]}   ------------> ${judge[2]}" 
     if [ "${judge[1]}"=="200" ] &&  [ "${judge[2]}"=="OK" ];then 
        action "${array[$i]}   ------------> ${judge[2]}"   /bin/true 
     else 
        action "${array[$i]}   ------------> ${judge[2]}"   /bin/false 
     fi 
  done 
} 
wait 
echo -e "/n" 
check_url

View Code

3. 数组的学习

Linux 下Shell的学习3-优秀demo详解程序员

 1 #!/bin/sh 
 2 #use array by 20170911 
 3 array=( 
 4     hello 
 5     world 
 6     2017 
 7     I  
 8     hava  
 9     a  
10     dream) 
11 arr=(`ls /home/omc/*.sh`) 
12 echo "---------------Array---------------------" 
13 for ((i=0;i<=${#array[*]};i++)) 
14 do 
15   echo "this is $i-------------------->${array[$i]}" 
16 done 
17   echo "------------------------------------" 
18   echo "total : ${#array[*]}" 
19 echo "---------------Ls *.sh--------------------" 
20 for((i=0;i<${#arr[*]};i++)) 
21 do 
22   echo "this is $i -------------------> ${arr[$i]}" 
23 done 
24   echo "------------------------------------" 
25   echo "total : ${#arr[*]}"

View Code

4. 监控WEB的URL

Linux 下Shell的学习3-优秀demo详解程序员

 1 [[email protected] scripts]# cat check_web.sh  
 2 #!/bin/sh 
 3 ######################################################## 
 4 RETVAL=0 
 5 SCRIPT_PATH="/root/scripts" 
 6 MAIL_GROUP="[email protected] [email protected]" 
 7 LOG_FILE="/tmp/web_check.log" 
 8 FAIL_COUNT=0 
 9 function getUrlState(){ 
10   for (( i = 0; i < 10; i++ )); do 
11     wget -T 10 --tries=1 --spider http://${URL} &>/dev/null 
12     [ $? -ne 0 ] && let ${FAIL_COUNT}+=1  
13   done   
14  
15 if [ ${FAIL_COUNT} -gt 1 ];then 
16     RETVAL=1 
17     NowTime=`date +%m-%d %H:%M:%S` 
18     TITLE="http://${URL} sevice is error,${NowTime}" 
19     echo "send to :${MAIL_USER},Title :${TITLE}" >>${LOG_FILE} 
20     for MAIL_USER in `$MAIL_GROUP` 
21     do 
22       mail -s ${TITLE}  ${MAIL_USER} <${LOG_FILE} 
23     done 
24 else 
25   RETVAL=0 
26 fi 
27 return "$RETVAL" 
28 } 
29  
30 [ ! -d "$SCRIPT_PATH" ] && { 
31   mkdir -p "$SCRIPT_PATH" 
32 } 
33  
34  
35  [ ! -f "$SCRIPT_PATH/domain.list" ] && { 
36    cat > "$SCRIPT_PATH/domain.list" << EOF 
37      www.baidu.com 
38      www.51cto.com 
39      www.http:www.hao123.com 
40 EOF 
41  } 
42    
43 for URL in `cat $SCRIPT_PATH/domain.list` 
44 do 
45   echo -n "checking $URL..." 
46   getUrlState $URL && echo OK || echo no 
47 done 
48 [[email protected] scripts]# 

View Code

5. for循环的使用

Linux 下Shell的学习3-优秀demo详解程序员

 1 方案一:计算某个access_log文件的访问总次数: 
 2 #!/bin/sh 
 3 num=`awk '{print $8}' $1 |grep -v eth0|awk -F '.' '{print $4}'` 
 4 sum=0 
 5 for line in $num 
 6 do 
 7   [ -n $line ] || continue 
 8   ((sum+=$line)) 
 9 done 
10 echo "Num is $sum" 
11  
12  
13 问题二:打印文件夹 
14 ls -F|grep / 
15  
16 问题三:打印文件夹 
17 #!/bin/sh 
18 openvpn="" 
19 openvpn_locations="/usr/bin/openvpn /usr/local/sbin/openvpn" 
20 for location in $openvpn_locations 
21 do 
22     [ -f $location ] && openvpn=$location  
23 done 
24  
25  
26 问题四:打印9*9 
27  
28 #!/bin/sh 
29 for a in `seq 1 9` 
30 do 
31     for b in `seq 1 9 ` 
32         do 
33            if [ $a -ge $b ];then 
34             echo -en "$a * $b = $(expr $a /* $b)" 
35            fi 
36         done 
37 echo " " 
38 done 
39  
40 问题5:编写连续IP的添加 
41 #!/bin/sh 
42  
43 print_usage(){ 
44   echo "USAGE: $0 {up/down}" 
45   exit 1 
46 } 
47  
48 [ $# -ne 1 ] && print_usage 
49  
50 ip_conf(){ 
51   for((i=1;i<=16;i++)) 
52   do 
53    if [ $i -ne 10 ];then 
54       ifconfig eth0:$i 192.168.25.$i netmask 255.255.255.0 $1 
55   else 
56     continue 
57   fi 
58 done 
59 } 
60  
61 case $1 in  
62   up) 
63     ip_conf;; 
64   down) 
65     ip_conf;; 
66   *) 
67     echo "something wrong..." 
68 esac

View Code

6. while循环的使用

Linux 下Shell的学习3-优秀demo详解程序员

 1 ------------------------------------------------------------------------------------------ 
 2 方案一: 
 3 #!/bin/sh 
 4 #cal 1 + 2 + 3 +...+100 
 5 i=10 
 6 while ((i>0)) 
 7 do 
 8   echo $i 
 9   ((i--)) 
10 done 
11 ------------------------------------------------------------------------------------------ 
12 方案二: 
13 #!/bin/sh 
14 #cal 1 + 2 + 3 +...+100 
15 i=10 
16 while [[ $i > 0]] 
17 do 
18   echo $i 
19   ((i--)) 
20 done 
21  
22 ------------------------------------------------------------------------------------------ 
23 方案三: 
24 #!/bin/sh 
25 #cal 1 + 2 + 3 +...+100 
26 i=10 
27 while ((i--)) 
28 do 
29   echo $i 
30 done 
31  
32  
33 ------------------------------------------------------------------------------------------ 
34 方案四: 
35 #!/bin/sh 
36 #cal 1 + 2 + 3 +...+100 
37 i=10 
38 while [ $i -gt 0] 
39 do 
40   echo $i 
41   ((i--)) 
42 done

View Code

7. 计算1+2+3+…+100

Linux 下Shell的学习3-优秀demo详解程序员

 1 方案1:for循环结构及(())计算式shell脚本 
 2 #!/bin/sh 
 3 #cal 1 + 2 + 3 +...+100 
 4 j=0 
 5 for ((i=0;i<=100;i++)) 
 6 do 
 7   ((j+=i)) 
 8 done 
 9  
10 echo "1 + 2 + 3 +...+100="$j 
11  
12 --------------------------------------------------------------------------------------- 
13 方案二:使用seq命令加for循环语法及let命令计算式脚本 
14 #!/bin/sh 
15 #cal 1 + 2 + 3 +...+100 
16 sum=0 
17 for i in `seq 100` 
18 do 
19   let sum+=i; 
20 done 
21 echo "1 + 2 + 3 +...+100="$sum     
22  
23 --------------------------------------------------------------------------------------- 
24 方案三:seqtrsed、bc联手完成计算的方法 
25  seq 100 | tr '/n' '+'|sed 's#/+$#/n#g'|bc    ==>拼接的字符串表达式结尾加号替换为换行(回车)符。 
26 --------------------------------------------------------------------------------------- 
27 方案四: 
28 #!/bin/sh 
29 i=1 
30 while ((i <=100 )) 
31 do 
32  ((j=j+i)) 
33  ((i++)) 
34 done 
35 echo $j 
36  
37 --------------------------------------------------------------------------------------- 
38 方案五: 
39 seq 100 |awk '{total+=$1} END {print total}'

View Code

8. case语句联系

Linux 下Shell的学习3-优秀demo详解程序员

 1 案例一: 纯case联系 
 2 #!/bin/sh 
 3 read -p "Please input the number of two:" num 
 4 case $num in  
 5   "1" ) 
 6    echo "the number you put is 1" ;; 
 7   "2") 
 8    echo "the number you put is 2";; 
 9   [3-9]) 
10    echo "the number you put is $num";; 
11   *) 
12     echo "something must be wrong ..."; 
13 esac 
14  
15  
16 案例二:case-if联系 
17 #!/bin/sh 
18 read -p "Please input the number of two:" num 
19 if [ $num -eq 1 ];then 
20     echo "1" 
21   elif [ $num -eq 2 ];then 
22     echo "2" 
23   elif [ $num -eq 3 ];then 
24     echo "3" 
25 else  
26   echo "$num"     
27 fi 
28  
29 案例三: 
30 #/bin/sh 
31 read -p "Please input the number of two:" fruit 
32 case "$fruit" in  
33     apple|APPLE) 
34         echo -e "Apple";;

View Code

8.1 if语句

Linux 下Shell的学习3-优秀demo详解程序员

 1 #!/bin/sh 
 2 #Author: ftl 
 3 #Date: 20170908 
 4  
 5 print_usage(){ 
 6     printf "please input 2 numbers:/n" 
 7     echo -e "$0 num1 num2" 
 8     exit 1 
 9 } 
10  
11 #judge num 
12 if [ $# -ne 2 ] 
13     then  
14         print_usage 
15 fi 
16  
17  
18 #judge num 
19 [ -n "`echo $1|sed 's/[0-9]//g' `" -a -n "`echo $2|sed 's/[0-9]//g'`" ] &&/ 
20     { 
21         echo "$1 $2 must be number" ; 
22         exit 1 
23     } 
24  
25 #judge body 
26 if [ $1 -gt $2 ] 
27     then  
28         echo "$1 > $2" 
29     elif [ $1 -eq $2 ] 
30         then 
31             echo "$1 = $2" 
32     else 
33         echo "$1 < $2" 
34 fi

View Code

9. nginx测试demo

Linux 下Shell的学习3-优秀demo详解程序员
View Code

10. 远程端口监控

Linux 下Shell的学习3-优秀demo详解程序员

 1 方案一: 
 2 nmap 检查 
 3  
 4 #!/bin/sh 
 5  
 6 httpPortNum=`nmap 192.168.25.138 -p 80|grep open|wc -l` 
 7 if [ $httpPortNum -eq 1 ]; then 
 8         echo "httpd is running..." 
 9 else 
10         echo "httpd is not running..." 
11         server httpd start 
12 fi 
13  
14  
15 方案二: 
16 wget -T 10 -q --spider http://192.168.25.138 &>/dev/null 
17 echo $? 
18  
19  
20 方案三: 
21 curl -I -s www.baidu.com |head -1|cut -d " " -f2 
22 if [ 200 -eq HTTPCODE ] 
23 echo $? 
24  
25 实际生产测试: 
26 #!/bin/sh 
27 HTTPCODE=`curl -I -s www.baidu.com |head -1|cut -d " " -f2` 
28 [ -f /etc/init.d/functions ] && . /etc/init.d/functions  || exit 1 
29 if [ "$HTTPCODE" -eq "200" ];then 
30     action "BaiDu/Nginx Http Server is Ok"  /bin/true 
31 else   
32     action "BaiDu/Nginx Http Server is Error" /bin/false 
33 fi 
34  
35 方案四: -->手动输入IP进行判断 
36 #!/bin/sh 
37  
38 if [ $# -ne 1 ]; then 
39   echo "USAGE: $0 IPADDR" 
40   exit 1 
41 fi 
42 HTTPCODE=`curl -I -s "$1"|head -1|cut -d " " -f2` 
43 [ -f /etc/init.d/functions ] && . /etc/init.d/functions  || exit 1 
44 if [ "$HTTPCODE" -eq "200" ];then 
45    action "BaiDu/Nginx Http Server "  /bin/true 
46 else   
47    action "BaiDu/Nginx Http Server"   /bin/false 
48  
49 fi 
50      
51 方案五  -->优化nmap 
52 #!/bin/sh 
53  
54 if [ $# -ne 2 ]; then 
55   echo "USAGE: $0 IPADDR PORT" 
56   exit 1 
57 fi 
58 HTTPCODE=`nmap $1 -p $2|sed -n '7p'|awk '{print $2}'`             -->也可以统计数量是否为1 
59 [ -f /etc/init.d/functions ] && . /etc/init.d/functions  || exit 1 
60 if [ "$HTTPCODE" == "open" ];then 
61    action "$1 on $2 port server " /bin/true 
62 else   
63    action "$1 on $2 port server " /bin/false 
64  
65 fi 
66  
67 方案六: 
68  
69 echo -e "/n"|telnet www.baidu.com 80|grep Connected|wc -l  -->可以执行完成第一个管道后执行换行命令 
70  
71 方案七: 
72 nc -w www.baidu.com 80 && echo ok

View Code

11. Mysql服务监控

Linux 下Shell的学习3-优秀demo详解程序员

 1 生成环境监控Mysqsl 
 2 方案1:过滤3306端口,查看是否启动正常 
 3     ps -ef|grep 3306 |grep -v grep   -->不建议,因为不太准,有的vi也是有显示结果的 
 4     netstat -lnput|grep 3306 
 5     netstat -lnput|grep 3306|wc -l   -->最常用的,如果为1,则表示开启,然后判读是否为1 if [ $port -eq 1 ] 
 6  
 7 方案2;Mysql端口和进程同时存在,则服务正常 
 8     PORT=`netstat -lnput|grep 3306|wc -l'`   
 9     PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l`  
10          
11 方案1: 
12 #!/bin/sh 
13 #Author: ftl 
14 #Mysql Monitor 
15  
16 PORT=`netstat -lnput|grep 3306|awk -F '[ :]+' '{print $5}'`  -->思路不是最佳 
17 if [ $PORT -eq 3306 ];then                      -->最还用字符串判断  if [ "$PORT" == "3306" ] 
18         echo "Mysql is Running ...." 
19 else 
20     service mysqld start 
21 fi 
22  
23  
24 方案2: 
25 #!/bin/sh 
26 #Author: ftl 
27 #Mysql Monitor 
28  
29 PORT=`netstat -lnput|grep 3306|wc -l`   
30 PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l` 
31 #if [ $PORT -eq 1 -a $PROCESS -eq 1 ];then      -->相等的                             
32 if [ $PORT -eq 1 ] && [ $PROCESS -eq 2 ];then     
33         echo "Mysql is Running ...." 
34 else 
35         service mysqld start 
36 fi 
37  
38  
39 实际的解决: 
40 #!/bin/sh 
41 #Author: ftl 
42 #Mysql Monitor 
43  
44 PORT=`netstat -lnput|grep 3306|wc -l` 
45 PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l` 
46 #if [ $PORT -eq 1 -a $PROCESS -eq 1 ];then      -->相等的                             
47 if [ $PORT -eq 1 ] && [ $PROCESS -eq 2 ];then 
48         echo "Mysql is Running ...." 
49 else       
50         service mysqld start 
51         sleep 10 
52         PORT=`netstat -lnput|grep 3306|wc -l` 
53         PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l` 
54         if [ $PORT -eq 1 ] && [ $PROCESS -eq 2 ];then 
55               echo "Mysql is Running ...." 
56            else 
57                 while true  
58                      do 
59                         pkill mysqld >/dev/null 2>&1  
60                         sleep 1 
61                         [ $? -ne 0 ] && break 
62                      done 
63         fi 
64                 service mysqld start && echo 'mysql is running....' 
65 fi   
66  
67  
68  
69 方案3:模拟web服务器,根据mysql账户进行连接,然后根据返回在状态判断mysql是否启动 
70     mysql -uroot -proot -h localhost -e "select version()";  -->查看mysql版本 
71 #!/bin/sh 
72 #Author: ftl 
73 #Mysql Monitor 
74  
75 MYSQL_VERSION=`    mysql -uroot -proot -e "select version()" >/dev/null` 
76 if [ $? -eq 0 ];then     
77         echo "Mysql is Running ...." 
78 else 
79         service mysqld start 
80 fi 
81  
82  
83 方案4:更专业的写法 
84     用变量定义路径, 
85     执行的脚本前面加上x判断  [ -x $MYSQL_SHELL ] >$LOG_DIR 
86     mysql -uroot -proot -h localhost -e "select version()";   -->注意-h,用于远端的监控 
87  
88 方案5:最佳的,利用php/java来进行监控 
89      
90 <?php 
91     $link_id=mysql_connect('db_etiantian','bbs','root') or mysql_error(); 
92     if($link_id){ 
93         echo "mysql is Ok ,Congratulation"; 
94     }else{ 
95         echo "Sorry,you can see logs of mysql"; 
96         echo mysql_error(); 
97     } 
98 ?>    
99     

View Code

12. 菜单联系

Linux 下Shell的学习3-优秀demo详解程序员

 1 #!/bin/sh 
 2 # menu list for ftl by ftl 20170906 
 3  
 4 menu(){ 
 5         cat <<END 
 6         1.[install lamp] 
 7         2.[install lnmp] 
 8         3.[install mysql] 
 9         4.[install nfs] 
10         0.[exit] 
11 END 
12 } 
13 menu 
14 read a 
15 echo "you choose $a"

View Code

13. epxr小技巧

Linux 下Shell的学习3-优秀demo详解程序员

 1 1.判断扩展名: 
 2  
 3 if expr "hello.txt" : ".*/.txt"  -->判断文件拓展名是否为.txt  注意空格 
 4     ->为真,则输出   9   显示匹配后的字符数,包括.txt 
 5     ->为假,则输出非 0 
 6  
 7  
 8 2.判断是否是整数 
 9     read -p "Please input" 
10     expr $a + 0 &>/dev/null  
11     [ $? -eq 0 ] && echo int || echo char

View Code

14. let监听服务

Linux 下Shell的学习3-优秀demo详解程序员

 1 #/bin/sh 
 2 #Function  Monitor by ftl 2017-09-06 
 3  
 4 ServerMonitor(){ 
 5     #Monitro status 
 6     timeout=10 
 7     fails=0 
 8     success=0 
 9     while true 
10     do 
11         /usr/bin/wget --timeout=$timeout --tries=1 http://192.168.25.138 -q -0 /dev/null 
12         if [ $? -ne 0 ] 
13             then 
14                 let fails+=1; 
15                 success=0 
16             else 
17                 fails=0 
18                 let success=1 
19         fi 
20  
21         if [ $success -ge 1 ] 
22             then 
23                 exit 0 
24         fi 
25  
26         if [ $fails -ge 2 ] 
27             then 
28                 Critical="TMS is Wrong ,please Checking...." 
29                 echo ${Critical}|mutt -s "httpd down,please contact [email protected]" 
30         fi 
31     done 
32  
33 }

View Code

15. 用source解析命令的使用

Linux 下Shell的学习3-优秀demo详解程序员

 1 [[email protected] omc]# echo 'dir=`date +%F`'>qq.sh  
 2 [[email protected] omc]# sh qq.sh  
 3 [[email protected] omc]# echo $dir 
 4  
 5 [[email protected] omc]# bash qq.sh 
 6 [[email protected] omc]# echo $dir 
 7  
 8 [[email protected] omc]# source qq.sh 
 9 [[email protected] omc]# echo $dir    
10 2017-09-05 
11 [[email protected] omc]#  
12 说明:source将原来shell里面的东西作为结果传递给当前的shell去显示

View Code

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/3037.html

(0)
上一篇 2021年7月16日 01:37
下一篇 2021年7月16日 01:37

相关推荐

发表回复

登录后才能评论