スクリプトのコマンドラインオプション

スクリプトのコマンドラインオプション
$ cat test15.sh  
#!/bin/bash  
# extracting command line options as parameters  
#  
echo  
while [ -n "$1" ]  
do  
    case "$1" in  
    -a) echo "Found the -a option" ;;  
    -b) echo "Found the -b option" ;;  
    -c) echo "Found the -c option" ;;  
     *) echo "$1 is not an option" ;;
esac  
shift  
done  
$  
$ ./test15.sh -a -b -c -d

Found the -a option  
Found the -b option  
Found the -c option  
-d is not an option 
$  

-dコマンドラインオプションでデバッグまたはアンインストールを示します。それでは、一部のスクリプトのコマンドラインオプションにこれを含めると、なぜオプションではありませんか?

ベストアンサー1

-d表示するようにプログラムされたすべてを表し、必ずしも削除またはデバッグする必要はありません。たとえばcurl-dデータオプションがあります。スクリプトで-d有効なオプションではありません。オプションは-a-bおよびです-c。これらすべては基本的に何もしません。

while [ -n "$1" ]  
do  
    case "$1" in  
        -a) echo "Found the -a option" ;;  
        -b) echo "Found the -b option" ;;  
        -c) echo "Found the -c option" ;;  
         *) echo "$1 is not an option" ;;
    esac  
shift  
done  

サポートを追加するには、-dケースの説明に次のように追加する必要があります。

while [ -n "$1" ]  
do  
    case "$1" in  
        -a) echo "Found the -a option" ;;  
        -b) echo "Found the -b option" ;;  
        -c) echo "Found the -c option" ;;  
        -d) echo "Found the -d option" ;;
         *) echo "$1 is not an option" ;;
    esac  
shift  
done  

コマンドラインオプションを処理するより良い方法は、次のようなgetoptsものを使用することです。

while getopts abcd opt; do 
    case $opt in
        a) echo "Found the -a option";;
        b) echo "Found the -b option";;
        c) echo "Found the -c option";;
        d) echo "Found the -d option";;
        *) echo "Error! Invalid option!" >&2;;
    esac
done

abcd予想されるパラメータのリストです。
a- 引数のないオプションを確認すると、-aサポートされていないオプションにエラーが発生します。
a:--a引数を含むオプションを確認してください。サポートされていないオプションについてはエラーが発生します。このパラメータはOPTARG変数に設定されます。
abcd- サポートされていないオプションについては、オプション、、、、を-a確認してください。 - オプション、、、、を確認して、サポートされていないオプションのエラーを削除してください。-b-c-d
:abcd-a-b-c-d

opt現在のパラメータを設定する変数(case文にも使用されます)。

おすすめ記事