Tips and Tricks: The usage of xargs for kubectl
When performing the operation on the cluster, you may need to check/edit the pod or resource back and forth. Here is one of the useful linux command xargs to speed up your kubectl operation.
-
You have to check the pod status by checking log, but the pod NAME may not be identical.
$ kubectl -n hub get pod NAME READY STATUS RESTARTS AGE primehub-bootstrap-c9dng 1/1 Running 0 21h $ kubectl -n hub logs primehub-bootstrap-c9dng ...so you can just use like:
$ kubectl -n hub get pod --no-headers | cut -d' ' -f1 | xargs kubectl -n hub logskubectlhas--no-headersoption to output without header columncut -d' ' -fto get the first column after trimming spaces- the last pipeline pass
xargsstringsXto thekubectl -n hub logs Xlast parameter
-
You may have several Custom Resources, would like to delete them all.
$ kubectl get crd | grep primehub | cut -d' ' -f1 | xargs kubectl delete crd customresourcedefinition.apiextensions.k8s.io "datasets.primehub.io" deleted customresourcedefinition.apiextensions.k8s.io "images.primehub.io" deleted customresourcedefinition.apiextensions.k8s.io "instancetypes.primehub.io" deleted -
You want to dump the pod which is not Running/Completed.
$ kubectl -n kube-system get pod --no-headers | grep -v -e Running -e Completed | cut -d' ' -f1 | xargs -I {} bash -c 'kubectl -n kube-system get pod {} -o yaml > {}.yaml'- grep
-vfor inverse-match,-efor pattern bash -cmeans the commands are read fromstring
- grep