zoukankan      html  css  js  c++  java
  • Shell 命令行解析 getopt工具

    Linux下使用getopt工具进行命令行解析,可以同时处理长选项和短选项。

    NAME
           getopt - parse command options (enhanced)
    
    SYNOPSIS
           getopt optstring parameters
           getopt [options] [--] optstring parameters
           getopt [options] -o|--options optstring [options] [--] parameters
    

    使用方法:

    #!/bin/bash
    
    # -o表示段选项,--long表示长选项
    # 选项后面没有冒号表示没有参数,1个冒号表示必须有参数,2个冒号表示可选参数
    # 对于具有可选参数的选项,没有没有提供值,会返回一个空字符串,并且会占用一个位置
    
    TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: -n 'example.bash' -- "$@"`
    if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
    
    eval set -- "$TEMP"
    
    while true; do
        case "$1" in
            -a|--a-long)
                echo "Option a"
                shift
                ;;
            -b|--b-long)
                echo "Option b, argument \`$2'"
                shift 2
                ;;
            -c|--c-long)
                case "$2" in
                    "")
                        echo "Option c, no argument"
                        shift 2
                        ;;
                    *)
                        echo "Option c, argument \`$2'"
                        shift 2
                        ;;
                esac
                ;;
            --)
                shift
                break
                ;;
            *) 
                echo "Internal error!"
                exit 1
                ;;
        esac
    done
    
    echo "Remaining arguments:"
    for arg do
       echo '--> '"\`$arg'" ;
    done
    

    双横岗的含义:

    例如:set -- "$progname" "$@"

    From help set:

      --  Assign any remaining arguments to the positional parameters.
          If there are no remaining arguments, the positional parameters
          are unset.
    

    The reason for -- is to ensure that even if "$progname" or "$@" contain dashes, they will not be interpreted as command line options.

    set changes the positional parameters, which is stored in $@. So in this case, it appends "$progname" to the beginning of the positional parameters received by the script.

  • 相关阅读:
    Alpha冲刺(2/10)——2019.4.25
    Alpha冲刺(1/10)——2019.4.24
    Alpha冲刺——序言篇(任务与计划)
    团队作业第六次—团队Github实战训练
    团队第四次作业答辩——反思与总结
    团队作业第五次—项目系统设计与数据库设计
    项目Alpha冲刺--6/10
    项目Alpha冲刺--5/10
    项目Alpha冲刺--4/10
    项目Alpha冲刺--3/10
  • 原文地址:https://www.cnblogs.com/jmliao/p/13227262.html
Copyright © 2011-2022 走看看