2013-10-02 36 views
2

所以我一直在閱讀有關getopts,getopt等的知識,但是我沒有找到解決我的問題的確切解決方案。在bash腳本中解析參數的最佳方法

我如何使用腳本的基本思路是:

./program [-u] [-s] [-d] <TEXT> 

除了文本,如果-d傳遞不是必需的。請注意,TEXT通常是一段文字。

我的主要問題是,一旦getopts完成解析標誌,我無法知道TEXT參數的位置。我姑且認爲文字是最後一個參數,但是,如果用戶食堂和不一樣的東西:

./program -u "sentence 1" "sentence 2" 

程序將沒有意識到,使用不正確。

我來最接近的是通過做

ARGS=$(getopt usd: $*) 
IFS=' ' read -a array <<< "$ARGS" 

唯一的問題使用的getopt和IFS是,文本可能是文本的長款和這種方法由於分割空間的文本的每一個字。

我想我最好的選擇是使用正則表達式,以確保正確地形成使用情況,然後提取與getopts的參數,但如果有一個簡單的解決方案

+0

命令行參數通常是短字符串。考慮從標準輸入中讀取來代替''。 – chepner

+0

您引用的示例中的用法不正確?什麼是正確的輸入? – rici

+0

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

回答

0

它會很高興這是什麼我通常做的:

local badflag="" 
local aflag="" 
local bflag="" 
local cflag="" 
local dflag="" 

while [[ "$1" == -* ]]; do 
    case $1 in 
    -a) 
     aflag="-a" 
     ;; 

    -b) 
     bflag="-b" 
     ;; 

    -c) 
     cflag="-c" 
     ;; 

    -d) 
     dflag="-d" 
     ;; 

    *) 
     badflag=$1 
     ;; 
    esac 
    shift 
done 

if [ "$badflag" != "" ]; do 
    echo "ERROR CONDITION" 
fi 

if [ "$1" == "" ] && [ "$dflag" == "" ]; do 
    echo "ERROR CONDITION" 
fi 

local [email protected] 
+2

這個(dis)的優點是你不能將單字母選項分組在一起;您必須明確使用每個選項,並在腳本的下一個參數中使用任何選項參數。因此,你不能模擬'ls -ls'或'sort -ooutput',而使用'getopts',你可以。 –

2

這是一個與getopts很簡單:

#!/bin/bash 
u_set=0 
s_set=0 
d_set=0 
while getopts usd OPT; do 
    case "$OPT" in 
    u) u_set=1;; 
    s) s_set=1;; 
    d) d_set=1;; 
    *) # getopts produces error 
     exit 1;; 
    esac 
done 
if ((!d_set && OPTIND>$#)); then 
    echo You must provide text or use -d >>/dev/stderr 
    exit 1 
fi 
# The easiest way to get rid of the processed options: 
shift $((OPTIND-1)) 
# This will run all of the remaining arguments together with spaces between them: 
TEXT="$*"