Bashスクリプトのエラーチェック

Bashスクリプトのエラーチェック

${deleteOldBranchRemote}エラーがないときに条件付きで実行されるようにこのスクリプトをどのように修正しますか${getRename}

Now_hourly=$(date +%d%b%H%M)
#echo "$Now_hourly"

newrcName="rc$Now_hourly"
#rename rc to the new name
getRename="git branch -m $newrcName"
#Delete the old-name remote branch
deleteOldBranchRemote="git push origin --delete rc"
${getRename}
#if getRename has error then do not execute the following line
#if [ $noErrorSomehowIneedToCheckForErrors ]
  #then
    ${deleteOldBranchRemote}
#fi

ベストアンサー1

次のように書くことができます。

if git branch -m $newrcName; then
    git push origin --delete rc
fi

したがって、2番目のコマンドは、最初のコマンドが終了コード0(成功を示す)で終わる場合にのみ実行されます。

を実行すると、ifキーワードに関する詳細情報を取得できますhelp if。私のシステムの出力例(Bash 4.3.46(1) - リリース):

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.

The `if COMMANDS' list is executed.  If its exit status is zero, then the
`then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list is
executed in turn, and if its exit status is zero, the corresponding
`then COMMANDS' list is executed and the if command completes.  Otherwise,
the `else COMMANDS' list is executed, if present.  The exit status of the
entire construct is the exit status of the last command executed, or zero
if no condition tested true.

Exit Status:
Returns the status of the last command executed.

エラーコードを知りたい場合は$? Bashは、この変数で実行された最後のコマンドの終了コードを保存します。後で使用するために変数に保存できます。

git branch -m $newrcName
BRANCH_EXIT_CODE=$?
echo "git branch -m $newrcName exit code was $BRANCH_EXIT_CODE"
# $? now contains the exit code of the preceding echo
if [ $BRANCH_EXIT_CODE -eq 0 ]; then
    git push origin --delete rc
fi

おすすめ記事