tmux_ram_info.sh
1 #!/usr/bin/env bash 2 # setting the locale, some users have issues with different locales, this forces the correct one 3 export LC_ALL=en_US.UTF-8 4 5 current_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 6 source "$current_dir/utils.sh" 7 8 get_cpids_linux() { 9 local ppid="$1" 10 local cpids 11 local cpid 12 echo "$ppid" 13 cpids="$(pgrep -P "$ppid")" 14 for cpid in $cpids; do 15 get_cpids_linux "$cpid" 16 done 17 } 18 19 get_cpids_unix() { 20 local ppid="$1" 21 local cpids 22 local cpid 23 echo "$ppid" 24 cpids="$(pgrep -aP "$ppid")" 25 for cpid in $cpids; do 26 get_cpids_unix "$cpid" 27 done 28 } 29 30 kb_to_mb() { 31 if [ $# == 0 ]; then 32 read -r num 33 else 34 num="$1" 35 fi 36 bc <<< "scale=3;$num/1024" 37 } 38 39 kb_to_gb() { 40 if [ $# == 0 ]; then 41 read -r num 42 else 43 num="$1" 44 fi 45 bc <<< "scale=6;$num/1048576" 46 } 47 48 round() { 49 if [ $# == 1 ]; then 50 read -r num 51 scale="$1" 52 elif [ $# == 2 ]; then 53 num="$1" 54 scale="$2" 55 fi 56 printf "%.${scale}f" "${num}" 57 } 58 59 get_tmux_ram_usage() 60 { 61 local pid 62 local pids 63 local total_mem_kb=0 64 local total_mem_mb=0 65 local total_mem_gb=0 66 pid="$(tmux display-message -pF '#{pid}')" 67 case $(uname -s) in 68 Linux) 69 if command -v pstree > /dev/null; then 70 pids="$(pstree -p "$pid" | tr -d '\n' | sed -rn -e 's/[^()]*\(([0-9]+)\)[^()]*/\1,/g' -e 's/,$//p')" 71 else 72 pids="$(get_cpids_linux "$pid" | tr '\n' ',')" 73 fi 74 total_mem_kb="$(ps -o rss= -p "$pids" | paste -sd+ | bc)" 75 ;; 76 77 Darwin) 78 if command -v pstree > /dev/null; then 79 pids="$(pstree "$pid" | sed -En 's/[^0-9]+([0-9]+) .*/\1/p' | tr '\n' ',')" 80 else 81 pids="$(get_cpids_unix "$pid" | tr '\n' ',')" 82 fi 83 total_mem_kb="$(ps -o rss= -p "$pids" | paste -sd+ - | bc)" 84 ;; 85 86 FreeBSD) 87 # TODO check FreeBSD compatibility 88 if command -v pstree > /dev/null; then 89 pids="$(pstree "$pid" | sed -En 's/[^0-9]+([0-9]+) .*/\1/p' | tr '\n' ',')" 90 else 91 pids="$(get_cpids_unix "$pid" | tr '\n' ',')" 92 fi 93 total_mem_kb="$(ps -o rss= -p "$pids" | paste -sd+ - | bc)" 94 ;; 95 96 CYGWIN*|MINGW32*|MSYS*|MINGW*) 97 # TODO - windows compatability 98 ;; 99 esac 100 total_mem_mb=$(kb_to_mb "$total_mem_kb" | round 0) 101 total_mem_gb=$(kb_to_gb "$total_mem_kb" | round 0) 102 103 if (( total_mem_gb > 0)); then 104 echo "${total_mem_gb}GB" 105 elif (( total_mem_mb > 0 )); then 106 echo "${total_mem_mb}MB" 107 else 108 echo "${total_mem_kb}kB" 109 fi 110 } 111 112 main() 113 { 114 ram_label=$(get_tmux_option "@dracula-tmux-ram-usage-label" "MEM") 115 ram_usage=$(get_tmux_ram_usage) 116 echo "$ram_label $ram_usage" 117 } 118 119 #run main driver 120 main