Skip to main content
ubuntuask.com

Back to all posts

How to Get Memory Usage For A Pid In A Variable Using Bash?

Published on
6 min read
How to Get Memory Usage For A Pid In A Variable Using Bash? image

Best Tools to Monitor Memory Usage to Buy in October 2025

1 General Tools DSM403SD Sound Level Meter with Data Logging SD Card, Class 1 Sound

General Tools DSM403SD Sound Level Meter with Data Logging SD Card, Class 1 Sound

  • ACCURATE MEASUREMENT: COVERS 30-130 DB WITH A/C WEIGHTING OPTIONS.
  • EASY DATA STORAGE: SAVE MEASUREMENTS DIRECTLY TO EXCEL VIA SD CARD.
  • VERSATILE APPLICATIONS: IDEAL FOR NOISE CONTROL AND REGULATORY COMPLIANCE.
BUY & SAVE
$438.58 $499.99
Save 12%
General Tools DSM403SD Sound Level Meter with Data Logging SD Card, Class 1 Sound
2 Extech RHT10 Humidity and Temperature USB Datalogger with 16,000 Data Point Memory, Dew Point, Time/Date Stamp, Long-Term Environmental Monitoring

Extech RHT10 Humidity and Temperature USB Datalogger with 16,000 Data Point Memory, Dew Point, Time/Date Stamp, Long-Term Environmental Monitoring

  • HIGH-PRECISION MONITORING: TRACKS HUMIDITY (0-100%) & TEMP (-40 TO 158°F).

  • EXTENSIVE DATA STORAGE: 16,000 READINGS WITH TIMESTAMPS FOR EASY REVIEW.

  • EASY DATA TRANSFER: USB INTERFACE FOR QUICK PC CONNECTION & ANALYSIS.

BUY & SAVE
$122.15
Extech RHT10 Humidity and Temperature USB Datalogger with 16,000 Data Point Memory, Dew Point, Time/Date Stamp, Long-Term Environmental Monitoring
3 harayaa Pupilometer Optical Digital PD Ruler LCD Screen with Memory Function Eye Ophthalmic Tool Interpupillary Distance Scale

harayaa Pupilometer Optical Digital PD Ruler LCD Screen with Memory Function Eye Ophthalmic Tool Interpupillary Distance Scale

  • COMPACT & PORTABLE DESIGN; EASY TO TAKE ANYWHERE, ANYTIME!
  • INDIVIDUAL EYE MEASUREMENTS FOR TAILORED, ACCURATE RESULTS.
  • USER-FRIENDLY LCD DISPLAY FOR EFFORTLESS READING AND TESTING.
BUY & SAVE
$40.29
harayaa Pupilometer Optical Digital PD Ruler LCD Screen with Memory Function Eye Ophthalmic Tool Interpupillary Distance Scale
4 Bittwee OBD II Memory Saver Connector, ECU Emergency Power Supply Cable with Alligator Clip, Battery Storage Digital Display Voltage Tool, Maintain Data Car Battery Leakage Detective

Bittwee OBD II Memory Saver Connector, ECU Emergency Power Supply Cable with Alligator Clip, Battery Storage Digital Display Voltage Tool, Maintain Data Car Battery Leakage Detective

  • DURABLE BUILD: HIGH-QUALITY COPPER AND SILICONE ENSURE LONG-LASTING USE.

  • EASY SETUP: QUICK INSTALLATION SAVES TIME WHEN REPLACING CAR BATTERIES.

  • VERSATILE USE: FITS VARIOUS VEHICLES; PROTECTS SETTINGS DURING BATTERY CHANGES.

BUY & SAVE
$8.59 $9.39
Save 9%
Bittwee OBD II Memory Saver Connector, ECU Emergency Power Supply Cable with Alligator Clip, Battery Storage Digital Display Voltage Tool, Maintain Data Car Battery Leakage Detective
5 MEASUREMAN 2” Air Pressure Gauge, 0-15 PSI, Black Steel Case, Red Memory Pointer, Brass Fittings, Durable Plastic Lens, Radial Mount for Accurate Pressure Monitoring

MEASUREMAN 2” Air Pressure Gauge, 0-15 PSI, Black Steel Case, Red Memory Pointer, Brass Fittings, Durable Plastic Lens, Radial Mount for Accurate Pressure Monitoring

  • PRECISE READINGS: 2 DIAL MEASURES 0-15 PSI FOR ACCURATE MONITORING.
  • BUILT TO LAST: MATTE BLACK STEEL CASE RESISTS CORROSION AND TOUGH WEAR.
  • TRACK EASILY: RED MEMORY POINTER FOR QUICK PEAK PRESSURE TRACKING.
BUY & SAVE
$14.97
MEASUREMAN 2” Air Pressure Gauge, 0-15 PSI, Black Steel Case, Red Memory Pointer, Brass Fittings, Durable Plastic Lens, Radial Mount for Accurate Pressure Monitoring
6 X AUTOHAUX OBD2 Male to Cigarette Lighter Memory Saver Emergency Power Supply Cable Diagnostic Tool Adapter Connector Cable

X AUTOHAUX OBD2 Male to Cigarette Lighter Memory Saver Emergency Power Supply Cable Diagnostic Tool Adapter Connector Cable

  • REAL-TIME CAR DATA ACCESS AND PROBLEM DETECTION WITH OBD CONNECTION.
  • DURABLE, WATERPROOF DESIGN ENSURES LONG-LASTING, RELIABLE PERFORMANCE.
  • EASY PLUG-AND-PLAY SETUP FOR HASSLE-FREE OBD2 SCANNER INTEGRATION.
BUY & SAVE
$8.79 $9.33
Save 6%
X AUTOHAUX OBD2 Male to Cigarette Lighter Memory Saver Emergency Power Supply Cable Diagnostic Tool Adapter Connector Cable
+
ONE MORE?

To get memory usage for a specific process ID (PID) in a variable using bash, you can use the following command:

mem_usage=$(ps -p $PID -o %mem | awk 'NR==2 {print $1}')

Replace $PID with the process ID for which you want to get the memory usage. This command uses the ps command to show information about processes, the -p flag to specify the process ID, the -o %mem flag to display the memory usage in percentage, and awk to extract and store the memory usage in a variable called mem_usage.

How to graph memory usage of a process using Bash plotting libraries?

There are several Bash plotting libraries that can be used to graph memory usage of a process. One popular option is gnuplot, which can be used to create simple line graphs to visualize memory consumption over time.

Here is an example script that utilizes gnuplot to graph memory usage of a process:

#!/bin/bash

Process ID of the target process

PID=1234

Output file for storing memory usage data

OUTPUT_FILE="memory_usage.dat"

Command to fetch memory usage of the process

FETCH_MEMORY="ps -p $PID -o %mem --no-headers"

Interval between data points in seconds

INTERVAL=1

Number of data points to collect

NUM_POINTS=60

Start timestamp

START=$(date +%s)

Create an empty data file

echo "# Timestamp Memory" > $OUTPUT_FILE

Loop to collect memory usage data

for ((i=1; i<=$NUM_POINTS; i++)) do MEMORY=$($FETCH_MEMORY) TIMESTAMP=$(date +%s) echo "$TIMESTAMP $MEMORY" >> $OUTPUT_FILE sleep $INTERVAL done

Generate the plot

gnuplot << EOF set terminal png set output 'memory_usage_plot.png' set title 'Memory Usage of Process $PID' set xlabel 'Time (s)' set ylabel 'Memory (%)' set datafile separator ' ' plot '$OUTPUT_FILE' using 1:2 with lines title 'Memory Usage' EOF

In this script:

  • Replace the PID variable with the process ID of the target process.
  • Specify the INTERVAL and NUM_POINTS variables to control the frequency and duration of data collection.
  • The script collects memory usage data using the ps command and saves it to a data file (memory_usage.dat).
  • The gnuplot commands generate a line graph from the data file and save it as memory_usage_plot.png.

Run the script in a Bash terminal to see the memory usage graph of the specified process. The resulting graph will show the memory consumption of the process over time.

How to get detailed memory usage statistics for a specific process in bash?

You can use the "ps" command in combination with other commands to get detailed memory usage statistics for a specific process in bash. Here's how you can do it:

  1. First, find the PID (Process ID) of the process you want to get memory usage statistics for. You can do this by using the "ps aux" command and grepping for the process name. For example, if you want to find the PID of a process named "myprocess", you can use the following command:

ps aux | grep myprocess

  1. Once you have the PID of the process, you can use the "pmap" command to get detailed memory statistics for that process. Simply replace "PID" with the actual PID of the process you want to monitor. For example:

pmap -x PID

This command will show you a detailed breakdown of memory usage for the specified process, including the total memory usage, shared memory, private memory, and more.

Alternatively, you can also use the "smem" command to get memory usage statistics for a specific process. You can use the following command to view memory usage for a specific process by specifying the PID:

smem -p PID

This command will display memory usage statistics for the specified process, including RSS (Resident Set Size), PSS (Proportional Set Size), Shared memory, and Private memory.

How to check memory usage of a process and its child processes in bash?

You can use the ps command along with the h flag to check the memory usage of a specific process and its child processes in bash.

Here is a command you can use to check the memory usage of a process and its child processes:

ps h -o pid --ppid | xargs ps u

Replace <PID> with the process ID of the parent process you want to check the memory usage for. This command will list the memory usage of the parent process and all its child processes.

There is no one-size-fits-all answer to this question as the recommended threshold for memory usage before considering optimization can vary depending on the specific requirements of your application and the available hardware resources.

However, a common rule of thumb is to consider optimization when memory usage is consistently close to or exceeding 80-90% of available memory. This threshold indicates that there may be potential issues with memory management, efficiency, or resource allocation that could benefit from optimization techniques such as improving data structures, reducing memory leaks, or optimizing algorithms.

Ultimately, it is important to closely monitor memory usage and performance metrics for your application to determine when optimization is necessary to ensure optimal performance and resource utilization.

What is the algorithm used to calculate memory usage statistics in Linux?

The algorithm used to calculate memory usage statistics in Linux is based on the information provided by the kernel's /proc filesystem. The kernel keeps track of various memory statistics, such as total available memory, memory usage by processes, cache and buffer memory usage, and swap space usage.

When calculating memory usage statistics, Linux takes into consideration the following memory metrics:

  1. Total memory - total physical memory available to the system
  2. Free memory - amount of memory not currently in use
  3. Used memory - total memory used by processes and the kernel
  4. Cached memory - memory used for caching disk data
  5. Buffer memory - memory used for temporary storage of data
  6. Swap memory - amount of memory swapped to disk

The calculation of memory usage statistics may vary slightly depending on the specific tool or command used to retrieve the information, such as free, top, or vmstat. Overall, these tools collect information from the /proc filesystem and analyze it to provide a comprehensive view of memory usage on the system.

How to display memory usage of a process in a human-readable format using bash?

You can display the memory usage of a process in a human-readable format using the following command in bash:

ps -p -o %mem

Replace <PID> with the process ID of the process whose memory usage you want to display.

This command will show the memory usage of the specified process in percentage format. If you want to display the memory usage in a more human-readable format, you can use the awk command to convert the output into gigabytes. Here's an example:

ps -p -o %mem | awk 'NR==2{print $1, "%"; printf "Memory Usage: %.2fGB\n", $1/100*$(free -m | awk '/Mem:/ {print $2}') }'

This command will display the memory usage of the process in percentage and also in gigabytes.