YBee24 / Yasmina-and-Lucien-Shell-Problem-Project-Friday-26-July

0 stars 0 forks source link

create top 3 memory usage function #10

Open Luciensday opened 3 months ago

YBee24 commented 3 months ago

Good morning!

Can you help me write some Linux code for the following function, please?


Good morning! I'd be happy to help you write a Bash function that finds the top 3 processes using the most memory on a Linux system. We can achieve this using the ps command, which provides a snapshot of current processes, combined with sorting and selecting the top results.

Here's a Bash function that accomplishes this task:


#!/bin/bash

# Function to find the top 3 memory-consuming processes
find_top_memory_processes() {
    echo "Top 3 memory-consuming processes:"

    # Use ps to get processes sorted by memory usage
    ps aux --sort=-%mem | awk 'NR==1 || NR<=4 {printf "%-10s %-8s %-8s %-8s %s\n", $1, $2, $3, $4, $11}'

    # Explanation of commands:
    # ps aux             : List all processes with detailed information
    # --sort=-%mem       : Sort the output by memory usage in descending order
    # awk 'NR==1 ...'    : Use awk to format and filter the output
    # NR==1              : Print the header (first row)
    # NR<=4              : Print the top 3 processes (plus the header)
    # printf ...         : Format the output to display relevant columns
}

# Call the function
find_top_memory_processes