Bashスクリプトのパラメータを効率的に確認するには?

Bashスクリプトのパラメータを効率的に確認するには?

私はBashスクリプトを書いたが、独学でbashを学んだ初心者なので、与えられた引数をより効率的にチェックできるかどうかを尋ねたかった。私もこの問題をグーグルしてここでトピックを確認しましたが、これまでに見た例は複雑すぎます。 Python3にははるかに簡単な方法がありますが、bashではもう少し複雑です。

#!/bin/bash

ERR_MSG="You did not give the argument required"

if [[ ${1?$ERR_MSG} == "a" ]]; then
        echo "ABC"
elif [[ ${1?$ERR_MSG} == "b" ]]; then
        echo "123"
elif [[ ${1?$ERR_MSG} == "c" ]]; then
        echo ".*?"
else
    echo "You did not provide the argument correctly"
    exit 1
fi

ベストアンサー1

abまたは次の1つのパラメータのみを許可するスクリプトc

#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo 'Too many/few arguments, expecting one' >&2
    exit 1
fi

case $1 in
    a|b|c)  # Ok
        ;;
    *)
        # The wrong first argument.
        echo 'Expected "a", "b", or "c"' >&2
        exit 1
esac

# rest of code here

正しいオプションを解析したい場合、引数のあるオプションだけでなく、引数のないオプションとして、またはを-a許可-bしたい場合。-c-d

#!/bin/bash

# Default values:
opt_a=false
opt_b=false
opt_c=false
opt_d='no value given'

# It's the : after d that signifies that it takes an option argument.

while getopts abcd: opt; do
    case $opt in
        a) opt_a=true ;;
        b) opt_b=true ;;
        c) opt_c=true ;;
        d) opt_d=$OPTARG ;;
        *) echo 'error in command line parsing' >&2
           exit 1
    esac
done

shift "$(( OPTIND - 1 ))"

# Command line parsing is done now.
# The code below acts on the used options.
# This code would typically do sanity checks,
# like emitting errors for incompatible options, 
# missing options etc.

"$opt_a" && echo 'Got the -a option'
"$opt_b" && echo 'Got the -b option'
"$opt_c" && echo 'Got the -c option'

printf 'Option -d: %s\n' "$opt_d"

if [[ $# -gt 0 ]]; then
    echo 'Further operands:'
    printf '\t%s\n' "$@"
fi

# The rest of your code goes here.

テスト:

$ ./script -d 'hello bumblebee' -ac
Got the -a option
Got the -c option
Option -d: hello bumblebee
$ ./script
Option -d: no value given
$ ./script -q
script: illegal option -- q
error in command line parsing
$ ./script -adboo 1 2 3
Got the -a option
Option -d: boo
Further operands:
        1
        2
        3

オプションの解析は、オプションではなく最初の引数で終了します---dパラメータは必須であるため、-a次の例では対応するパラメータとして扱われます。

$ ./script -d -a -- -c -b
Option -d: -a
Further operands:
        -c
        -b

おすすめ記事