Bash:「&」を使用してバックグラウンドでスクリプトを実行し、「||」を使用して失敗したときに他のものを実行する方法は?

Bash:「&」を使用してバックグラウンドでスクリプトを実行し、「||」を使用して失敗したときに他のものを実行する方法は?

バックグラウンドでコマンドを実行しようとしていますが、最初のコマンドが失敗した場合は、「||」を使用して別のコマンドを実行します。例:

$( <run-this-in-background> & || <run-this-if-failed>)

しかし、構文エラーが発生します。:

command substitution: line 15: syntax error near unexpected token `||'

正確な内容は次のとおりです。

$(./temptwo.sh & || rc=$?)

私の完全なコードは次のとおりです。rc=$?次の行でこれを行うことができれば少し奇妙に見えますが、私たちはロガーを使用しており、$?で終わる行があるとプログラムは終了します。 != 0 なので、この問題に対する解決策は "0" で終了しますが、戻りコードも提供する "./someCommand || rc=$?" を使用することです。

#default success code: 
rc=0 
#run temptwo.sh in the background. If it fails, set rc=$?
$(./temptwo.sh & || rc=$? )
#Trying to get the process id of "temptwo.sh" below (not sure if works)
pid=$! 
#Wait until the process finishes
wait $pid 

ベストアンサー1

/temptwo.sh & pid=$! ; wait $pid || rc=$?

しかし、IMHOはあまり意味がありません。

/temptwo.sh & pid=$! ; wait $pid ; rc=$?
if [ "$rc" -gt 0 ]; then
...

おすすめ記事