淡淡回忆 发表于 2018-8-21 08:40:55

在shell脚本中提供帮助的例子

在脚本中提供帮助是一种很好的编程习惯,这样方便其他用户(和您)使用和理解脚本。 查看一下我们实际中经常使用的脚本。  请注意我们重点要学习的是方法如下:
  6 case "$0" in
  7    *start)
  8         ;;
  9    *)
  10         echo $"Usage: $0 {start}"
  11         exit 1
  12         ;;
  13 esac
  这种方式也是在Linux的一些服务脚本中经常使用到的。例如我们输入错误的选项后会有帮助信息返回:
  # service network NoThisOption
  Usage: /etc/init.d/network {start|stop|restart|reload|status}
  或者:
  # service nothisservice
  nothisservice: unrecognized service
  很容易发现service也只是一个脚本,我们很轻松地查看它的代码。
  # file `which service`
  /sbin/service: Bourne shell script text executable
  下面我们就以在Linux、UNIX中经常用到的killall脚本来说明一下实现的手段。
  一、这个是在RHEL中提供的killall的脚本,用来杀死一些不允许强制停止的服务。
  # vim /etc/rc.d/init.d/killall
  1 #! /bin/bash
  2
  3 # Bring down all unneeded services that are still running (there shouldn't
  4 # be any, so this is just a sanity check)
  5
  6 case "$1" in
  7    *start)
  8         ;;
  9    *)
  10         echo $"Usage: $0 {start}"
  11         exit 1
  12         ;;
  13 esac
  14
  15
  16 for i in /var/lock/subsys/* ; do
  17         # Check if the script is there.
  18         [ -f "$i" ] || continue
  19
  20         # Get the subsystem name.
  21         subsys=${i#/var/lock/subsys/}
  22
  23         # Networking could be needed for NFS root.
  24         [ $subsys = network ] && continue
  25
  26         # Bring the subsystem down.
  27         if [ -f /etc/init.d/$subsys.init ]; then
  28               /etc/init.d/$subsys.init stop
  29         elif [ -f /etc/init.d/$subsys ]; then
  30               /etc/init.d/$subsys stop
  31         else
  32               rm -f "$i"
  33         fi
34 done 二、下面的这个例子是使用函数来实现的,这样的内容更具有可读性,帮助的容量也可以更大  1 #!/bin/sh
  2 # vim: set sw=4 ts=4 et:
  3
  4 help()
  5 {
  6 cat
页: [1]
查看完整版本: 在shell脚本中提供帮助的例子