uriid1

Get process ram usage [Linux, Bash]

Jul 1st, 2022 (edited)
1,067
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env bash
  2.  
  3. ####--------------------------------####
  4. #--# Author:   by uriid1            #--#
  5. #--# License:  GNU GPL              #--#
  6. #--# Telegram: @foxdacam            #--#
  7. #--# Mail:     appdurov@gmail.com   #--#
  8. ####--------------------------------####
  9.  
  10. # Program name: puse
  11. # Version: 1.0
  12.  
  13. # Install:
  14. # chmod +x puse
  15. # Copy this script for ~/.local/bin/
  16.  
  17. # Use:
  18. # puse process_name
  19. # or
  20. # puse -p pid
  21.  
  22. # Args check
  23. if [ $# -eq 0 ]; then
  24.     echo "[Error]: The first argument is missing"
  25.     exit
  26. fi
  27.  
  28. # Root check
  29. if [ "$EUID" -ne 0 ]
  30.     then echo "[Error]: Please run as root"
  31.     exit
  32. fi
  33.  
  34. # Variable
  35. pname=$1
  36. pid=-1
  37. re='^[0-9]+$'
  38.  
  39. # If the PID is specified
  40. if [ "-p" == $1 ]; then
  41.     if [ -z "$2" ]; then
  42.         echo "[Error]: The second argument is missing"
  43.         exit
  44.     fi
  45.  
  46.     # Second arg not a number
  47.     if ! [[ $2 =~ $re ]]; then
  48.         echo "[Expected number]: Invalid second argument format received"
  49.         exit
  50.     fi
  51.  
  52.     # Set PID
  53.     pid=$2
  54. fi
  55.  
  56. # Check pidof installed
  57. if [ "$pid" -eq -1 ]; then
  58.     if [ -x "$(command -v pidof)" ]; then
  59.         pid=$(pidof $pname)
  60.     else
  61.         pid=$(ps aux | grep $pname | awk '{print $2}')
  62.     fi
  63. fi
  64.  
  65. # If we have received a list of PIDs, then we take the last one
  66. IFS=' ' read -r -a array <<< "$pid"
  67. pid="${array[-1]}"
  68.  
  69. # If you suddenly got a wrong number
  70. if ! [[ $pid =~ $re ]]; then
  71.    echo "[Error]: Invalid PID format received"
  72.    echo Receive: $pid
  73.    exit
  74. fi
  75.  
  76. # Calculate
  77. k_usage=$(pmap $pid | tail -n 1 | sed -e 's/[^0-9]//g')
  78.  
  79. # Name check
  80. if [ $pname == '-p' ]; then
  81.     name=$(ps aux | grep $pid | awk '{print $1}')
  82.     IFS='\n' read -r -a arr_name <<< "$name"
  83.     pname="${arr_name[-1]}"
  84. fi
  85.  
  86. # Show info
  87. echo "Name:" $pname "PID:" $pid
  88. echo $k_usage "Kb"
  89. echo $(($k_usage/1000)) "Mb"
RAW Paste Data Copied