<p>What is the best way to wait for kubernetes job to be complete?  I noticed a lot of suggestions to use:</p>
<pre><code>kubectl wait --for=condition=complete job/myjob
</code></pre>
<p>but i think that only works if the job is successful. if it fails, i have to do something like:</p>
<pre><code>kubectl wait --for=condition=failed job/myjob
</code></pre>
<p>is there a way to wait for both conditions using wait?  if not, what is the best way to wait for a job to either succeed or fail?</p>

<p>Run the first wait condition as a subprocess and capture its PID. If the condition is met, this process will exit with an exit code of 0.</p>
<pre class="lang-bash prettyprint-override"><code>kubectl wait --for=condition=complete job/myjob &amp;
completion_pid=$!
</code></pre>
<p>Do the same for the failure wait condition. The trick here is to add <code>&amp;&amp; exit 1</code> so that the subprocess returns a non-zero exit code when the job fails.</p>
<pre class="lang-bash prettyprint-override"><code>kubectl wait --for=condition=failed job/myjob &amp;&amp; exit 1 &amp;
failure_pid=$!
</code></pre>
<p>Then use the Bash builtin <code>wait -n $PID1 $PID2</code> to wait for one of the conditions to succeed. The command will capture the exit code of the first process to exit:</p>
<blockquote>
<p>MAC USERS! Note that <code>wait -n [...PID]</code> requires Bash version 4.3 or higher. MacOS is forever stuck on version 3.2 due to license issues. Please see this <a href="https://stackoverflow.com/a/11704224/3745474">Stackoverflow Post</a> on how to install the latest version.</p>
</blockquote>
<pre class="lang-bash prettyprint-override"><code>wait -n $completion_pid $failure_pid
</code></pre>
<p>Finally, you can check the actual exit code of <code>wait -n</code> to see whether the job failed or not:</p>
<pre class="lang-bash prettyprint-override"><code>exit_code=$?

if (( $exit_code == 0 )); then
  echo &quot;Job completed&quot;
else
  echo &quot;Job failed with exit code ${exit_code}, exiting...&quot;
fi

exit $exit_code
</code></pre>
<p>Complete example:</p>
<pre class="lang-bash prettyprint-override"><code># wait for completion as background process - capture PID
kubectl wait --for=condition=complete job/myjob &amp;
completion_pid=$!

# wait for failure as background process - capture PID
kubectl wait --for=condition=failed job/myjob &amp;&amp; exit 1 &amp;
failure_pid=$! 

# capture exit code of the first subprocess to exit
wait -n $completion_pid $failure_pid

# store exit code in variable
exit_code=$?

if (( $exit_code == 0 )); then
  echo &quot;Job completed&quot;
else
  echo &quot;Job failed with exit code ${exit_code}, exiting...&quot;
fi

exit $exit_code
</code></pre>
