2012-06-27 82 views
3

我正在尋找一個可重用的代碼片斷,它爲bash執行命令行參數驗證。Bash的命令行參數驗證庫

理想一些類似於由Apache的百科全書CLI提供的功能:

共享CLI支持不同類型的選擇:

  • POSIX類似的選項
  • (即焦油-zxvf的foo.tar.gz。)
  • GNU等長選項(即杜--human可讀--max深度= 1)
  • 短選項附值(即GCC -O2 foo.c的)
  • 長選項與單個連字符(即。螞蟻-projecthelp)
  • ...

,並自動生成程序中的「用法」的消息,像這樣:

usage: ls 
-A,--almost-all   do not list implied . and .. 
-a,--all     do not hide entries starting with . 
-B,--ignore-backups  do not list implied entried ending with ~ 
-b,--escape    print octal escapes for nongraphic characters 
    --block-size <SIZE> use SIZE-byte blocks 
-c      with -lt: sort by, and show, ctime (time of last 
          modification of file status information) with 
          -l:show ctime and sort by name otherwise: sort 
          by ctime 
-C      list entries by columns 

我將包括之初此代碼段我Bash腳本並跨腳本重用它。

一定有這樣的事情。我不相信我們都編寫代碼來這種效果或類似:

#!/bin/bash 

NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS=3 

number_of_supplied_command_line_arguments=$# 

function show_command_usage() { 
    echo usage: 
    (...) 
} 

if ((number_of_supplied_command_line_arguments < NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS)); then 
    show_command_usage 
    exit 
fi 

... 
+3

使用'getopts'作爲簡短選項。參見[BashFAQ/35](http://mywiki.wooledge.org/BashFAQ/035)。用Python編寫腳本並使用[argparse](http://docs.python.org/library/argparse.html)。 –

+0

我懷疑答案是缺乏模塊基礎結構使得以可移植的方式加載源庫與每次重寫選項解析大致相同的工作量。 – tripleee

回答

5

這是我使用的解決方案(發現它在網絡上的某個地方,也許在這裏本身,不記得是肯定的)。請注意,GNU getopt(/usr/bin/getopt)確實支持使用選項-a的單短劃線長選項(ant -projecthelp樣式),但是我沒有使用它,因此它在示例中未顯示。

此代碼解析爲3個選項:--host value-h value--port value-p value--table value-t value。在情況下所需的參數沒有被設置,因爲它的測試是

# Get and parse options using /usr/bin/getopt 
OPTIONS=$(getopt -o h:p:t: --long host:,port:,table: -n "$0" -- "[email protected]") 
# Note the quotes around `$OPTIONS': they are essential for handling spaces in 
# option values! 
eval set -- "$OPTIONS" 

while true ; do 
    case "$1" in 
      -h|--host) HOST=$2 ; shift 2 ;; 
      -t|--table)TABLE=$2 ; shift 2 ;; 
      -p|--port) 
        case "$2" in 
          "") PORT=1313; shift 2 ;; 
          *) PORT=$2; shift 2 ;; 
        esac;; 
      --) shift ; break ;; 
      *) echo "Internal error!" ; exit 1 ;; 
    esac 
done 
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then 
    usage() 
    exit 
if 

使用getopts殼內建的替代實現(這隻支持小選項):

while getopts ":h:p:t:" option; do 
    case "$option" in 
     h) HOST=$OPTARG ;; 
     p) PORT=$OPTARG ;; 
     t) TABLE=$OPTARG ;; 
     *) usage(); exit 1 ;; 
    esac 
done 
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then 
    usage() 
    exit 
if 

shift $((OPTIND - 1)) 

進一步閱讀爲GNU getoptgetopts bash builtin