首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将帮助方法添加到shell脚本?

如何将帮助方法添加到shell脚本?
EN

Stack Overflow用户
提问于 2011-03-29 23:06:51
回答 7查看 167.9K关注 0票数 147

如何检查-h属性是否已传递到shell脚本中?我想在用户调用myscript.sh -h时显示一条帮助消息。

EN

回答 7

Stack Overflow用户

发布于 2011-03-29 23:11:00

shell脚本的第一个参数可以作为变量$1使用,因此最简单的实现是

代码语言:javascript
复制
if [ "$1" == "-h" ]; then
  echo "Usage: `basename $0` [somestuff]"
  exit 0
fi

但是阿努巴瓦说了什么。

票数 52
EN

Stack Overflow用户

发布于 2015-06-14 22:03:41

下面是我用它来启动VNC服务器的一部分

代码语言:javascript
复制
#!/bin/bash
start() {
echo "Starting vnc server with $resolution on Display $display"
#your execute command here mine is below
#vncserver :$display -geometry $resolution
}

stop() {
echo "Killing vncserver on display $display"
#vncserver -kill :$display
}

#########################
# The command line help #
#########################
display_help() {
    echo "Usage: $0 [option...] {start|stop|restart}" >&2
    echo
    echo "   -r, --resolution           run with the given resolution WxH"
    echo "   -d, --display              Set on which display to host on "
    echo
    # echo some stuff here for the -a or --add-options 
    exit 1
}

################################
# Check if parameters options  #
# are given on the commandline #
################################
while :
do
    case "$1" in
      -r | --resolution)
          if [ $# -ne 0 ]; then
            resolution="$2"   # You may want to check validity of $2
          fi
          shift 2
          ;;
      -h | --help)
          display_help  # Call your function
          exit 0
          ;;
      -d | --display)
          display="$2"
           shift 2
           ;;

      -a | --add-options)
          # do something here call function
          # and write it in your help function display_help()
           shift 2
           ;;

      --) # End of all options
          shift
          break
          ;;
      -*)
          echo "Error: Unknown option: $1" >&2
          ## or call function display_help
          exit 1 
          ;;
      *)  # No more options
          break
          ;;
    esac
done

###################### 
# Check if parameter #
# is set too execute #
######################
case "$1" in
  start)
    start # calling function start()
    ;;
  stop)
    stop # calling function stop()
    ;;
  restart)
    stop  # calling function stop()
    start # calling function start()
    ;;
  *)
#    echo "Usage: $0 {start|stop|restart}" >&2
     display_help

     exit 1
     ;;
esac

我把start、stop、restart放在一个单独的情况下,这有点奇怪,但它应该可以工作

票数 32
EN

Stack Overflow用户

发布于 2011-03-29 23:08:41

最好使用bash的getopt工具。请查看此问答以获取更多帮助:Using getopts in bash shell script to get long and short command line options

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5474732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档