2015-07-02 45 views
1
TABLE=`echo "${1}" | tr '[:upper:]' '[:lower:]'` 
if [ $1 = -d ] 
    then TABLE=daminundation 
elif [ $1 = -b ] 
    then TABLE=burnscararea 
elif [ $1 = -r ] 
    then TABLE=riverpointinundation 
elif [ $1 = " " ] 
    then echo "User must input -d (daminundation), -b (burnscararea) 
    or -r (riverpointinundation)." 
fi 
SHAPEFILEPATH=${2} 
MERGEDFILENAME=${3} 
if [ -z $3 ] ; 
    then MERGEDFILENAME=merged.shp 
else 
    MERGEDFILENAME=${3} 
fi 
COLUMNNAME=${4} 
if [ -n $4 ] 
    then COLUMNNAME=$4 
fi 

$ 3 & $ 4是可選參數。但是,如果我選擇不使用$ 3,但我想使用$ 4,則它將以$ 3的形式讀取命令。對於其他方法感到困惑,我應該如何做到這一點,以避免下一個不需要的可選命令被繞過?如何在bash中繞過以下參數的可選參數?

+1

'./your_script.sh PARAM_1 PARAM_2 「」 param_4' –

+2

您正在尋找[getopts的(http://wiki.bash-hackers.org/howto/ getopts_tutorial) –

+0

@LucM第一個選項適用於一個簡單的解決方案,getopts似乎是更有組織的解決方案。謝謝。 – muse

回答

1

你可能想這樣的:

#!/bin/bash 

while getopts ":b :d :r" opt; do 
    case $opt in 
    b) 
     TABLE=burnscararea 
     ;; 
    d) 
     TABLE=daminundation 
     ;; 
    r) 
     TABLE=riverpointinundation 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     exit 1 
     ;; 
    esac 
done 

shift $((OPTIND-1)) 

[ -z "$TABLE" ] && (echo "At least one of -b/-d/-r options must be provided"; exit 1;) 
[ $# -ne 3 ] && (echo "3 params expected!"; exit 1;) 
SHAPEFILEPATH="$2" 
MERGEDFILENAME="$3" 
COLUMNNAME="$4" 
# other stuff 
+0

儘管這並沒有解決第三個和第四個參數以及表格的第一個參數,但它提供了我需要的解決方案的工作模板。欣賞它! – muse