基本パラメータを提供する非常に単純なラッパーを作成する方法は?

基本パラメータを提供する非常に単純なラッパーを作成する方法は?

たとえば、いくつかのパラメータを必要とするプログラムがある場合、これらのパラメータのprogram -in file.in -out file.out有無にかかわらず呼び出すことができ、各パラメータにデフォルト値を使用するbashスクリプトを書く最も簡単な方法は何ですか?

script -in otherfile走ることができるprogram -in otherfile -out file.out
script -out otherout -furtherswitch走ることができるprogram -in file.in -out otherout -furtherswitch、等。

ベストアンサー1

Bashでデフォルト値を定義するのは簡単です。

foo="${bar-default}" # Sets foo to the value of $bar if defined, "default" otherwise
foo="${bar:-default}" # Sets foo to the value of $bar if defined or empty, "default" otherwise

パラメータを処理するには、単純なループを使用できます。

while true
do
    case "${1-}" in
        -in)
            infile="${2-}"
            shift 2
            ;;
        -out)
            outfile="${2-}"
            shift 2
            ;;
        *)
            break
            ;;
    esac
done

program -in "${infile-otherfile}" -out "${outfile-otherout}" "$@"

有用な材料:

getoptまた、コードを複雑で混乱させる可能性がある多くの特殊なケースを処理する能力のために使用することをお勧めします(重要な例)。

おすすめ記事