<p>I frequently encounter issues will kubectl port forwarding and want to write a bash script to auto-reconnect. How do you grep for something on a stream and &quot;fail&quot; when it's found? I've found questions like <a href="https://stackoverflow.com/questions/31816132/how-to-grep-a-continuous-stream-from-the-cli-and-exit-if-string-found">this</a> for &quot;tailing a file&quot; but I don't want to write the output of kubectl to a log file and use a separate process to tail - that feels too complicated. Also I'm aware that grep -q doesn't work on steams e.g. see <a href="https://stackoverflow.com/questions/7178888/grep-q-not-exiting-with-tail-f">here</a>.</p>
<p>So far I have tried this:</p>
<pre><code>kubectl port-forward deployment/haproxy 8080:8080 | grep -q --line-buffered error
</code></pre>
<p>Which correctly prints</p>
<pre><code>E0528 21:30:14.643696   95553 portforward.go:400] an error occurred forwarding 8080 -&gt; 8080: error forwarding port 8080 to pod 7aa1822dab53ddd732bc8fdc9575e1820ab476be2be097a472eb838f5eec22b2, uid : exit status 1: 2021/05/29 01:30:14 socat[13287] E connect(5, AF=2 127.0.0.1:1883, 16): Connection refused
</code></pre>
<p>But how do I return after error so I can do something like this:</p>
<pre><code>while :
do
  kubectl port-forward deployment/haproxy 8080:8080 | grep -q --line-buffered error | return on error
  echo &quot;port forwarding failed trying again!&quot;
done
</code></pre>

<p>How about.</p>
<pre><code>#!/usr/bin/env bash

if kubectl port-forward deployment/haproxy 8080:8080 2&gt;&amp;1 |
  grep -Fq --line-buffered error; then
  printf &gt;&amp;2 &quot;port forwarding failed trying again!\n&quot; &amp;&amp;
  exit 
fi 
</code></pre>
<p>If it is inside a loop, replace <code>exit</code> with <code>break</code>.</p>
