Quick Linux Tip #58 - How to Profile Memory Usage in a Bash Script

Quick Linux Tip #58:

Question: My bash script has a memory leak somewhere. How do I profile it?

Try: /usr/bin/time -v bash ./my_script.sh 2>&1 | grep -E 'Maximum|CPU|Elapsed|Voluntary'

Info: /usr/bin/time (GNU binary, not the shell builtin) with -v tracks detailed resource usage. Peak memory usage is shown under Maximum resident set size (Maximum RSS).

Examples:

  • $ /usr/bin/time -v ./program 2>time.log  # Log detailed resource statistics
  • $ /usr/bin/time -f '%M KB peak, %e sec, %P CPU' ./script.sh  # Custom resource output
  • $ valgrind --tool=massif ./program  # Memory profiling for compiled binaries

Note: The shell builtin time provides less detailed information, so /usr/bin/time is useful when you need GNU resource statistics. A high RSS value in a script can indicate that it is holding large files, arrays, or other data in memory. For a true memory-leak investigation, use a dedicated memory profiler such as Massif rather than relying on peak RSS alone.




LinuxTeck.com
linuxteck@ubuntu:~$ /usr/bin/time -v bash ./script.sh 2>&1 | grep -E 'Maximum|CPU|Elapsed|Voluntary'
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:12.34
        Percent of CPU this job got: 78%
        Maximum resident set size (kbytes): 234567
        Voluntary context switches: 4567
        Involuntary context switches: 234
linuxteck@ubuntu:~$

PREVIOUS ARTICLE Quick Linux Tip #57 - How to Connect Through Multiple SSH Jump Hosts
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.