<p>Basically I want to automate this task where I have some namespaces in Kubernetes I need to delete and others that I want to leave alone. These namespaces contain the word nginx. So I was thinking in order to do that I could get the output of <strong>get namespace</strong> using some regex and store those namespaces in an array, then iterate through that array deleting them one by one.</p>
<pre><code>array=($(kubectl get ns | jq -r 'keys[]'))
declare -p array
for n in {array};
do
    kubectl delete $n
done
</code></pre>
<p>I tried doing something like this but this is very basic and doesn't even have the regex. But I just left it here as an example to show what I'm trying to achieve. Any help is appreciated and thanks in advance.</p>

Jones
<p><code>kubectl get ns</code> doesn't output JSON unless you add <code>-o json</code>. This:</p>
<pre><code>array=($(kubectl get ns | jq -r 'keys[]'))
</code></pre>
<p>Should result in an error like:</p>
<pre><code>parse error: Invalid numeric literal at line 1, column 5
</code></pre>
<hr />
<p><code>kubectl get ns -o json</code> emits a JSON response that contains a list of <code>Namespace</code> resources in the <code>items</code> key. You need to get the <code>metadata.name</code> attribute from each item, so:</p>
<pre><code>kubectl get ns -o json | jq -r  '.items[].metadata.name'
</code></pre>
<hr />
<p>You only want namespaces that contain the word &quot;nginx&quot;. We could filter the above list with <code>grep</code>, or we could add that condition to our <code>jq</code> expression:</p>
<pre><code>kubectl get ns -o json | jq -r  '.items[]|select(.metadata.name|test(&quot;nginx&quot;))|.metadata.name'
</code></pre>
<p>This will output your desired namespaces. At this point, there's no reason to store this in array and use a <code>for</code> loop; you can just pipe the output to <code>xargs</code>:</p>
<pre><code>kubectl get ns -o json |
jq -r  '.items[]|select(.metadata.name|test(&quot;nginx&quot;))|.metadata.name' |
xargs kubectl delete ns
</code></pre>
