How to invert docker ps output

How

Step: Create a new bash script (“.docker_ps_invert.sh)

Bash
#!/bin/bash

# Define headers you're interested in
declare -a headers=("ID" "Image" "Command" "CreatedAt" "RunningFor" "Ports" "Status" "Names")

# Get the IDs of all running containers
container_ids=$(docker ps -q)

if [ -z "$container_ids" ]; then
  echo "No running containers found."
  exit 1
fi

# Initialize a counter
index=1

# Loop over each container ID
for container_id in $container_ids; do
    echo "($index) Container ID: $container_id"
    # Fetch container details for the current container ID
    container_details=$(docker ps --format "{{.ID}}\t{{.Image}}\t{{.Command}}\t{{.CreatedAt}}\t{{.RunningFor}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}" | grep $container_id)

    # Convert details to array
    IFS=$'\t' read -r -a details <<< "$container_details"

    # Print each header and its corresponding value
    for i in "${!headers[@]}"; do
      echo -e "${headers[$i]}\t${details[$i]}"
    done

    ((index++))
    
    echo "----------------------------------------------"
done

# thanks chatgpt

Step: allow executing

Bash
chmod +x .docker_ps_invert.sh

# create an alias if you want!
# .zshrc
alias dpi="~/.docker_ps_invert.sh"
inverted docker ps

Why?

  • sometimes the default “docker ps” output is hard to read because the super wide width of values causes line breaks

Alternative You can choose specific columns to show (like below)…

Bash
$ docker ps --format "table {{.ID}}\t{{.Image}}\t{{.CreatedAt}}"

But what if you want to see every column? That’s where the script about shines.