<p>I am writing a bash script and I need the kubectl command to get all the namespace in my cluster based on a particular label.</p>
<pre><code>kubectl get ns -l=app=backend
</code></pre>
<p>When I run the command above I get:
<code>no resources found</code></p>

Philcz
<blockquote>
<p>only the pods in the ns have that label. wondering if there's a way I can manipulate kubectl to output only the ns of the pods that have that label</p>
</blockquote>
<p>You can combine a few commands to do something like:</p>
<pre><code>kubectl get pods -A -l app=backend  -o json |
  jq -r '.items[]|.metadata.namespace' |
  sort -u
</code></pre>
<p>This gets a list of all pods in all namespaces that match the label selector; uses <code>jq</code> to extract the namespace name from each pod, and then uses <code>sort -u</code> to produce a unique list.</p>
<hr />
<p>You can actually do this without <code>jq</code> by using the <code>go-template</code> output format, but for me that always means visiting the go template documentation:</p>
<pre><code>kubectl get pods -A -l app=backend \
  -o go-template='{{range .items}}{{.metadata.namespace}}{{&quot;\n&quot;}}{{end}}' |
  sort -u
</code></pre>
