02 May 2022

How to sort the output of kubectl by a field

  • k8s
  • kubernetes
  • howto

One of the most common use cases for kubectl is to sort the output of the command. You can use the following command to sort the output of the command by a field.

kubectl get pods --sort-by=<field>

For example, I am listing the pods in the namespace kube-system sorted by the pod running age.

kubectl get po -n kube-system --sort-by='{.metadata.creationTimestamp}'

. represents the root of the json object of the output of the command. metadata.creationTimestamp represents the field of the json object.

The output looks as below

k8s sort by field

BTW, if you wondering how I got metadata.creationTimestamp from the output of the command, you can get the JSON object of the output of the command by using the following command.

kubectl get po -n kube-system -o json

Which will give you the following JSON output. You can use the any JSON field to sort the output as long as you reference it with correct hierarchy.

k8s sort by field json output