For each name and namespace

2/25/2019

I'm trying to run some bulk commands. In the below case I want to delete all pods which doesn't have the state running.

The piped input to xargs looks as below

ingress-nginx nginx-ingress-controller-b84c455b-5k48p
ingress-nginx nginx-ingress-controller-b84c455b-5kwsc
ingress-nginx nginx-ingress-controller-b84c455b-88tnp
ingress-nginx nginx-ingress-controller-b84c455b-q96rj
ingress-nginx nginx-ingress-controller-b84c455b-tb98v
ingress-nginx nginx-ingress-controller-b84c455b-v9xmw
kafka kafka-0
kafka zookeeper-2
kube-system kubernetes-dashboard-5946dfdf8d-hz7gk
kube-system kubernetes-dashboard-5946dfdf8d-sv5lb
logging es-data-1
...

I want to both values in the same command. My attempt looks as below

$ kubectl get pods --all-namespaces | \
                    grep -v Running | \
                          tr -s ' ' | \
                   cut -d" " -f 1,2 | \
                         tail -n +2 | \
         xargs -n 1 echo "cmd $1 $2"

The output is

cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-5k48p
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-5kwsc
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-88tnp
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-q96rj
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-tb98v
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-v9xmw
cmd   kafka
cmd   kafka-0
cmd   kafka
cmd   zookeeper-2
cmd   kube-system
cmd   kubernetes-dashboard-5946dfdf8d-hz7gk
cmd   kube-system
cmd   kubernetes-dashboard-5946dfdf8d-sv5lb
cmd   logging
cmd   es-data-1

Clearly I want a single command with both input values. Any suggestions on how to make that happen? Possible with a simpler command?

-- user672009
bash
kubernetes
xargs

2 Answers

2/25/2019

You can process two args with -n 2:

xargs -n 1 echo cmd

Specifying $1 and $2 doesn't work with xargs, the two parameters will be sent to the command automatically. In fact, they're the reason of the spaces after cmd in your output: they get interpreted by the shell before xargs sees them, and they expand to empty strings.

-- choroba
Source: StackOverflow

2/25/2019

Be sure to capture per-line (-L1) then let a shell take care of the $ parsing, i.e. below should work for you

xargs -L1 sh -c 'echo cmd $1 $2' --
-- jjo
Source: StackOverflow