1

Im pretty new to bash but im trying to learning. My question is:

Im running this ps to get the info and sending to /tmp/freememory.txt

#!/bin/bash
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head >/tmp/freememory.txt

cat   "/tmp/freememory.txt"

the output is

PID      PPID CMD                         %MEM %CPU
  859     1 /usr/lib/snapd/snapd         1.3  0.0
  890     1 /usr/bin/python3 /usr/share  0.9  0.0
  845     1 /usr/bin/python3 /usr/bin/n  0.8  0.0
  851     1 /usr/sbin/NetworkManager --  0.8  0.0
  300     1 /lib/systemd/systemd-journa  0.7  0.0
 1501     1 /usr/lib/packagekit/package  0.6  0.0
  996     1 /usr/bin/whoopsie -f         0.6  0.0
 3530     1 /usr/sbin/cups-browsed       0.5  0.0
  855     1 /usr/sbin/ModemManager --fi  0.4  0.0

Im learning arrays,so my idea is to create an array to show the same ouput:

ARRAY= (cat /tmp/freememory.txt)


echo ${ARRAY[@]}

But the output difficult to read

PID PPID CMD %MEM %CPU 859 1 /usr/lib/snapd/snapd 1.3 0.0 890 1 /usr/bin/python3 /usr/share 0.9 0.0 845 1 /usr/bin/python3 /usr/bin/n 0.8 0.0 851 1 /usr/sbin/NetworkManager -- 0.8 0.0 300 1 /lib/systemd/systemd-journa 0.7 0.0 1501 1 /usr/lib/packagekit/package 0.6 0.0 996 1 /usr/bin/whoopsie -f 0.6 0.0 3530 1 /usr/sbin/cups-browsed 0.5 0.0 855 1 /usr/sbin/ModemManager --fi 0.4 0.0

Its ther any way that the array output looks like the first output from(cat "/tmp/freememory.txt")?

Thanks

1 Answer 1

0

The bash shell only really supports 1d arrays - if you are content with an array of lines that's simple enough using the mapfile (aka readarray) builtin:

$ mapfile -t array < freememory.txt

$ printf '%s\n' "${array[@]}"
PID      PPID CMD                         %MEM %CPU
  859     1 /usr/lib/snapd/snapd         1.3  0.0
  890     1 /usr/bin/python3 /usr/share  0.9  0.0
  845     1 /usr/bin/python3 /usr/bin/n  0.8  0.0
  851     1 /usr/sbin/NetworkManager --  0.8  0.0
  300     1 /lib/systemd/systemd-journa  0.7  0.0
 1501     1 /usr/lib/packagekit/package  0.6  0.0
  996     1 /usr/bin/whoopsie -f         0.6  0.0
 3530     1 /usr/sbin/cups-browsed       0.5  0.0
  855     1 /usr/sbin/ModemManager --fi  0.4  0.0

Note the double quotes around "${array[@]}" to prevent word splitting. You can skip the file and read into the array directly from the ps pipeline if you prefer, using process substitution:

mapfile -t array < <(ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.