Bashスクリプトから2つのプログラムのうちの1つを選択してください

Bashスクリプトから2つのプログラムのうちの1つを選択してください

2台の異なるコンピュータで実行したい(bash)スクリプトがあります。 1つはOpenBSDsha256で、もう1つはsha256sum

sha256vsの場合は、sha256sumプログラムの他のオプションを変更する必要はありませんが、wgetvsなどの他のプログラム選択の場合は、curl他のパラメータが変更されます(例:wgetvs curl -O。)。したがって、最良の答えは、利用可能なプログラムに応じて異なるコマンドライン引数を許可することです。

プログラムを修正する1つの方法は、次のようにcommandhashまたはの終了状態に応じて変更される変数を使用することです。typeこの問題

例えば

SHA_PROGRAM=sha256
command -v "$SHA_PROGRAM"
# If the exit status of command is nonzero, try something else 
if [ "$?" -ne "0" ]; then
    command -v "sha256sum"
    if [ "$?" -ne "0" ]; then
        printf "This program requires a sha256 hashing program, please install one\n" 1>&2
        exit 1
    else
        SHA_PROGRAM=sha256sum
    fi 
fi
$SHA_PROGRAM $MYFILE

しかし、このアプローチは入れ子になったif文の問題は言うまでもなく、少し冗長に見えます。

一連の可能なコマンドを使用して一般化できます。

declare -a POSSIBLE_COMMANDS=("sha256" "sha256sum")
SHA_PROGRAM=""
for $OPT in "${POSSIBLE_COMMANDS[@]}"
do
    command -v "$OPT"
    # if the exit status of command is zero, set the command variable and exit the loop
    if [ "$?" -eq "0" ]; then
        SHA_PROGRAM=$OPT
        break
    fi
done 

# if the variable is still empty, exit with an error    
if [ -z "$SHA_PROGRAM" ]; then
    printf "This program requires a sha256 program. Aborting\n" 1>&2
    exit 1
fi

$SHA_PROGRAM $MY_FILE

||この方法も効果があると確信していますが、より良いソリューション(演算子を賢く使用する方法はありますか?)を見逃した場合に備えて、より経験豊富で、より良いbashプログラマーからアドバイスを得たいと思います。

ベストアンサー1

@yaegashiのコメントによると、これはif command -v ...; then ...平凡で単純な目標を達成したようです。

例:

# The SHA_CMD variable can be used to store the appropriate command for later use
SHA_CMD=""
if command -v sha256; then
    SHA_CMD=sha256
elif command -v sha256sum; then 
    SHA_CMD=sha256sum
else 
    printf "This program requires a a sha256 program installed\n" 1>&2
    exit 1
fi 
"$SHA_CMD" "$MY_FILE" > "$MY_FILE.sha"
# Note: if any of the possible sha commands had command line parameters, then the quotes need to be removed from around $SHA_CMD

おすすめ記事