Bash Function to Sort Docker Ps Output

Sorting the output of docker ps can be helpful when you’re managing multiple containers and need a clearer view of what’s running. In this tutorial, we’ll walk through creating a Bash function that organizes this output in a more readable way using built-in shell tools like awk and sort. This builds upon Docker basic commands like docker ps, docker images, and docker inspect to create more powerful container management tools.
  • How to integrate it into your shell environment
  • How to test and use the function in practice
Bash Function to Sort Docker Ps Output
Bash Function to Sort Docker Ps Output

Software Requirements and Linux Command Line Conventions

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions, or Software Version Used
System Linux (any distribution with Docker installed)
Software Docker, Bash Shell, awk
Other Text editor (e.g., nano, vim)
Conventions # – Run as root or with sudo
$ – Run as a regular user

Bash Functions to Sort Docker PS Output

DID YOU KNOW?
You can combine docker ps with Bash to filter, sort, and monitor your containers more effectively? For example, you can list only the newest containers, find those that have exited, or even create custom views by name or uptime. It’s a great way to stay in control when managing lots of containers!

Step-by-Step Instructions

What These Functions Do

These bash functions solve common Docker container management challenges:

  • docker_ps_sort – Alphabetically sorts your running containers by name while maintaining the table format. This helps you quickly locate specific containers in environments with many services.
  • docker_ps_sort_image – Sorts containers by image name, making it easy to identify all containers running the same image version. This is particularly useful for version control and update planning.

Below are the steps to create, apply, and test improved Bash functions for sorting docker ps output while maintaining proper table formatting.

  1. Create the Bash FunctionOpen your shell profile file (e.g., ~/.bashrc or ~/.bash_aliases) and add the following improved function:
    function docker_ps_sort() {
        docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Image}}" | 
        (read -r header && echo "$header" && sort)
    }

    This function preserves the header row at the top while sorting the container entries below it, giving you properly formatted output.

  2. Apply the ChangesReload your shell configuration to apply the new function:
    $ source ~/.bashrc

    Alternatively, you can run the function definition directly in your current shell session for immediate testing.

  3. Run the FunctionExecute the function to see sorted Docker container output with proper formatting:
    $ docker_ps_sort

    You’ll see output like this, with the header correctly positioned:

    Alphabetically sorts your running containers by name while maintaining the table format.
    Alphabetically sorts your running containers by name while maintaining the table format.

    Benefits of this function: The alphabetical container name sorting makes it much easier to:

    • Quickly locate a specific container by name in environments with many containers
    • Identify containers that belong to the same application or service (usually named with similar prefixes)
    • Scan the list more efficiently since it’s in a predictable order
    • Maintain consistent output in scripts or monitoring tools
  4. Customize the SortingIf you want to sort by a different field, such as image name, create another function with a modified format string:
    function docker_ps_sort_image() {
        docker ps --format "table {{.Image}}\t{{.Names}}\t{{.Status}}" | 
        (read -r header && echo "$header" && sort)
    }

    This function will produce output sorted by image name:

    Bash function to produce output sorted by docker image name
    Bash function to produce output sorted by docker image name

    Why this is useful: Sorting by image name helps you quickly identify which containers are running the same images. This can be invaluable when:

    • Planning image updates or security patches
    • Identifying containers running outdated image versions
    • Grouping related services that use the same base images
    • Auditing your environment for image standardization
  5. Advanced CustomizationYou can further customize the sorting by using additional commands:
    • Sort by specific column: Use sort -k2 to sort by the second column
    • Reverse the order: Add -r flag (sort -r)
    • Filter results: Add grep to show only specific containers
    function docker_ps_uptime() {
        # Sort containers by uptime (newest first)
        docker ps --format "table {{.Names}}\t{{.RunningFor}}\t{{.Status}}" | 
        (read -r header && echo "$header" && sort -k2 -r)
    }

    What this function does: The docker_ps_uptime function sorts containers by how long they’ve been running, showing the newest containers at the top. This is particularly useful when troubleshooting recently deployed containers or when you need to identify which containers might have restarted unexpectedly.

  6. Make It PermanentEnsure the functions are loaded in every session by keeping them in your shell configuration file. You can create a dedicated file for Docker functions:
    # In ~/.bashrc or ~/.zshrc
    if [ -f ~/.docker_functions ]; then
        source ~/.docker_functions
    fi

    Then place all your Docker functions in ~/.docker_functions for better organization.

Understanding the Key Components

  • The Table Format: The --format "table {{.Names}}\t{{.Status}}\t{{.Image}}" part creates a formatted table with the specified columns.
  • The Header Preservation: The (read -r header && echo "$header" && sort) part:
    • Creates a subshell with parentheses
    • Reads the first line (header) into a variable
    • Outputs that header first
    • Then sorts the remaining lines
  • Available Format Options: You can use any of these placeholders in your format string:
    • {{.ID}} – Container ID
    • {{.Names}} – Container name
    • {{.Image}} – Image name
    • {{.Status}} – Container status
    • {{.RunningFor}} – Time since container started
    • {{.Ports}} – Exposed ports
    • {{.Command}} – Command being run
    • {{.Size}} – Container size

More advanced docker ps command sorting bash functions

  1. Sort containers by memory usage: Find containers consuming the most memory
    docker_sort_by_mem() {
        docker stats --no-stream --format "{{.Name}}\t{{.MemPerc}}\t{{.ID}}" | \
        sort -k2 -nr | \
        awk 'BEGIN {print "CONTAINER NAME\tMEMORY USAGE\tCONTAINER ID"} {print $0}'
    }

    This function pulls memory usage statistics from all running containers and sorts them in descending order. The output shows container names, memory usage percentages, and container IDs, helping you quickly identify memory-intensive containers. This is particularly useful for resource optimization in production environments.

  2. List containers by uptime (oldest first): Display containers sorted by how long they’ve been running
    docker_sort_by_age() {
        docker ps --format "{{.CreatedAt}}\t{{.Names}}\t{{.RunningFor}}\t{{.Status}}" | \
        sort -k1 | \
        awk -F'\t' '{print $2 "\t" $3 "\t" $4}' | \
        column -t -s $'\t'
    }

    This function lists containers by uptime, showing the oldest running containers first. The output is formatted into columns for readability. This is helpful for identifying long-running containers that might need updates or rotation as part of maintenance procedures.

    Sort docker containers bash function by age
    Sort docker containers bash function by age
  3. Group containers by image: See which images have the most running containers
    docker_group_by_image() {
        docker ps --format "{{.Image}}" | \
        sort | \
        uniq -c | \
        sort -nr | \
        awk '{printf("%s containers using image %s\n", $1, $2)}'
    }

    This function groups and counts running containers by their base image, displaying results in descending order. This gives you a quick overview of which images are most deployed in your environment, which is useful for security audits or update planning.

  4. Find containers with port conflicts: Identify containers that might have overlapping port mappings
    docker_find_port_conflicts() {
        docker ps --format "{{.Names}}\t{{.Ports}}" | \
        grep -v "0.0.0.0" | \
        awk -F'->' '{print $1}' | \
        awk '{print $1 "\t" $NF}' | \
        sort -k2 | \
        awk '{
            port=$2;
            if(port==prev) {
                print "CONFLICT: " prev_name " and " $1 " both use " port;
            }
            prev=port;
            prev_name=$1;
        }'
    }

    This complex function analyzes port mappings across all containers to identify potential conflicts where multiple containers might be trying to use the same host port. It parses the output, extracts port information, and flags containers with matching port assignments, helping prevent unexpected behavior in networked applications.

  5. Monitor containers with high CPU spikes: Track containers exceeding a defined CPU threshold
    docker_monitor_cpu_spikes() {
        threshold=${1:-50}  # Default threshold of 50%
        
        watch -n 5 "docker stats --no-stream --format \"{{.Name}}\t{{.CPUPerc}}\t{{.MemPerc}}\" | \
        awk -v threshold=\"$threshold\" '\
        BEGIN {printf \"%-30s %-15s %-15s %-10s\\n\", \"CONTAINER\", \"CPU %\", \"MEM %\", \"STATUS\"}\
        {
            cpu=\$2; 
            sub(/%/, \"\", cpu); 
            if (cpu > threshold) {
                printf \"%-30s %-15s %-15s %-10s\\n\", \$1, \$2, \$3, \"WARNING\";
            } else {
                printf \"%-30s %-15s %-15s %-10s\\n\", \$1, \$2, \$3, \"OK\";
            }
        }'"
    }

    This monitoring function continuously checks for containers that exceed a specified CPU usage threshold (defaulting to 50% if not specified). It refreshes every 5 seconds and highlights containers with high CPU consumption, making it easy to identify performance issues in real-time during debugging or load testing scenarios.

  6. Analyze container networking: Sort containers by network traffic volume
    docker_sort_by_network() {
        docker stats --no-stream --format "{{.Name}}\t{{.NetIO}}" | \
        awk '{
            split($2, io, "/");
            # Extract numeric values and convert to bytes
            gsub(/[^0-9.]/, "", io[1]);
            if($2 ~ /kB/) io[1] *= 1024;
            if($2 ~ /MB/) io[1] *= 1024 * 1024;
            if($2 ~ /GB/) io[1] *= 1024 * 1024 * 1024;
            # Print with the calculated byte values for sorting
            printf "%s\t%s\t%.0f\n", $1, $2, io[1];
        }' | \
        sort -k3 -nr | \
        head -10 | \
        awk '{printf("%-30s %s\n", $1, $2)}'
    }

    This sophisticated function analyzes network I/O for all containers, converts the various units (kB, MB, GB) to a common scale, sorts by the highest network traffic, and displays the top 10 bandwidth-consuming containers. This is invaluable for identifying containers that might be experiencing network bottlenecks or abnormal traffic patterns.

  7. Health status dashboard: Create a colored overview of container health status
    docker_health_dashboard() {
        docker ps --format "{{.Names}}\t{{.Status}}" | \
        awk '{
            container_name = $1;
            # Remove the first field and preserve the rest as status
            $1 = "";
            status = $0;
            
            printf "%s\t", container_name;
            
            if (status ~ /\(unhealthy\)/) {
                printf "\033[31mUNHEALTHY\033[0m\n";
            } else if (status ~ /\(healthy\)/) {
                printf "\033[32mHEALTHY\033[0m\n";
            } else if (status ~ /Up/ && status !~ /health/) {
                printf "\033[33mUP (NO HEALTH CHECK)\033[0m\n";
            } else if (status ~ /Restarting/) {
                printf "\033[35mRESTARTING\033[0m\n";
            } else {
                printf "\033[31mCRITICAL\033[0m\n";
            }
        }' | \
        column -t -s $'\t'
    }

    This function creates a colorful health dashboard showing the status of all containers with intuitive color coding: green for healthy, red for unhealthy, yellow for running without health checks, and purple for restarting containers. This provides a quick visual overview of your container fleet’s health, making it easy to spot issues at a glance.

    Health status dashboard docker bash function
    Health status dashboard docker bash function

Conclusion

This Bash function improves your workflow when managing multiple Docker containers. It’s especially useful on busy systems and helps you quickly identify important containers based on sorting logic you define.

Frequently Asked Questions (FAQ)

  1. Can I sort by CPU or memory usage?

    Not directly with docker ps, but you can use docker stats with custom scripts or tools like ctop.

  2. Will this work on Zsh or Fish?

    You may need to adjust syntax slightly depending on your shell, but the concept remains the same.

  3. Can I use this for remote Docker hosts?

    Yes, if your Docker client is set to communicate with a remote host, the function works just the same.

  4. What if I want to filter specific containers?

    You could add a grep command before the sort to filter container names or statuses based on your needs.

  5. How can I improve the functionality further?

    Consider integrating error handling and additional sorting options based on your typical usage scenarios.

 



Comments and Discussions
Linux Forum