Search code examples
bashxargs

in bash and xargs loop on nlines after pipe


Team, my below command, greps for any pods with problems then takes them one by one and deletes.

But I want to use only first 10 lines of my command output.

kubectl get pods --all-namespaces | grep -i -e Evict -e Error | 
    awk -F ' ' '{print $1, $2, $4}' | 
    xargs -l1 -- sh -c 'kubectl delete pod "$2" -n "$1"' --

above command is deleting for all rows but i want to do only for first 10 rows. any hint?

i tried

kubectl get pods --all-namespaces | grep -i -e Evict -e Error | 
    awk -F ' ' '{print $1, $2, $4}' | for run{1..10}; do 
        xargs -l1 -- sh -c 'kubectl delete pod "$2" -n "$1" ' --; 
    done

once, i know this, i can use it for any command node or pod.


Solution

  • You can use head to get the first 10 lines of output before passing to xargs. Use the -n option to specify how many lines (in this case, head -n10)

    Just before piping to xargs, insert the following: | head -n10 |. This will filter everything but the first ten lines of preceding output.

    Try this:

    kubectl get pods --all-namespaces | grep -i -e Evict -e Error | awk -F ' ' '{print $1, $2, $4}' | head -n10 | xargs -l1 -- sh -c 'kubectl delete pod "$2" -n "$1"' --