2014-03-14 81 views
1

我已經爲/bin/sh posix shell創建了一個腳本,該腳本使用getopts實用程序處理標誌,現在我意識到它可能不是我的最佳選擇,它是外部依賴性,最終它甚至沒有那麼靈活,對於長度爲1個字符的標誌可能是好的,但是我想要使用更多「詳細」和直觀的標誌,如--config--value-for-a=42在沒有getopts的情況下處理shell腳本的標誌

假設我想實施一些自包含的東西,那麼有什麼選擇?

+0

'getopts'是一個內置的shell,而不是外部的依賴項。 –

+0

[在bash shell腳本中使用getopts來獲取長和短命令行選項](http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long -and-short-command-line-options) –

+0

@ shon shell中的@JonathanLeffler?你確定 ?無論如何,我必須使用更長的標誌 – user2485710

回答

1

這是一個快速和骯髒的方法:

根據需要
AAA=default 
# example: BBB left unspecified so you can optionally override from environment 
XYZ=${XYZ:-0} # optional so you could override from environment 
ABC=${ABC:-0} 
while test $# -gt 0 ; do 

    # switches 
    if test "$1" = "--flag-xyz" ; then XYZ=1 ; shift ; continue; fi 
    if test "$1" = "--flag-abc" ; then ABC=1 ; shift ; continue; fi 

    # options with arguments 
    case "$1" in 
    --option-aaa=*) AAA="${1##--option-aaa=}" ; shift; continue; break ;; 
    --option-bbb=*) BBB="${1##--option-bbb=}" ; shift; continue; break ;; 
    esac 

    # unknown - up to you - positional argument or error? 
    echo "Unknown option $1" 
    shift 
done 

自定義。

這種方法的優點是獨立於順序,您可以根據需要調整語法邊緣案例的選項。否則就很簡單。

如果您需要強制執行排序,則需要時將處理分解爲多個語句,並從while語句中斷開。

缺點是getopt有時會避免一些重複。

編輯:更改[==]和-gt測試

+0

這個腳本主要用於'bash',它不適用於'sh'。 – user2485710

+0

我以爲我只是測試它拍 (挖左右) 偷偷摸摸的,Linux的我已經在我的面前符號鏈接的/ usr/bin/sh的 - > /斌/慶典 你不能使用相同的雖然方法,只是語法會有點不同? – 6EQUJ5

+0

看看http://www.freebsd.org/cgi/man.cgi?sh sh支持case,shift,esac,break,繼續$#和$ {##} - 大概只是'=='那就是缺失?編輯正在發生...... – 6EQUJ5

相關問題