<p>I want to make a command which can clear all old deployments. For example, I have deployments in a namespace</p>
<blockquote>
<p>kubectl -n web get deploy --sort-by=.metadata.creationTimestamp</p>
</blockquote>
<pre><code>myproject-static-staging-master                  1/1     1            1           54d
myproject-static-staging-task-13373                1/1     1            1           20d
myproject-static-staging-task-13274                1/1     1            1           19d
myproject-static-staging-task-13230                1/1     1            1           19d
myproject-static-staging-task-13323                1/1     1            1           19d
myproject-static-staging-task-13264                1/1     1            1           18d
myproject-static-staging-task-13319                1/1     1            1           13d
myproject-static-staging-task-13470                1/1     1            1           6d20h
myproject-static-staging-task-13179                1/1     1            1           6d20h
myproject-static-staging-task-13453                1/1     1            1           6d4h
myproject-static-staging-moving-to-old           1/1     1            1           6d
myproject-static-staging-moving-test             1/1     1            1           5d20h
</code></pre>
<p>I want to save only that's (5 newest)</p>
<pre><code>myproject-static-staging-task-13470                1/1     1            1           6d20h
myproject-static-staging-task-13179                1/1     1            1           6d20h
myproject-static-staging-task-13453                1/1     1            1           6d4h
myproject-static-staging-moving-to-old           1/1     1            1           6d
myproject-static-staging-moving-test             1/1     1            1           5d20h
</code></pre>
<p>I tried that command</p>
<blockquote>
<p>kubectl get deployment -n web --template '{{range
.items}}{{.metadata.name}}{{&quot;\n&quot;}}{{end}}'
--sort-by=.metadata.creationTimestamp | grep -v master | grep myproject-static-staging | head -n 5 | xargs -r kubectl -n web delete
deployment</p>
</blockquote>
<p>but it is no correct.</p>

<p>You can use xargs command like this:</p>
<pre><code>command1 | xargs -I{} command2 {}
</code></pre>
<p>Xargs will replace the output from command1 with the empty {}. For example, if the output of command1 is '1 2 3', then Xargs will invoke commands: 'command2 1', 'command2 2', and 'command2 3'.</p>
<p>So in your case, you can use</p>
<pre><code>kubectl get deployment -n web --template '{{range .items}}{{.metadata.name}}{{&quot;\n&quot;}}{{end}}' --sort-by=.metadata.creationTimestamp | grep -v master | grep myproject-static-staging | tail -r | tail -n +6 | xargs -I{} kubectl -n web delete deployment {}
</code></pre>
<p>'tail -r' will reverse the order, and 'tail -n +6' will select all rows except the first 5.</p>
