0

I am trying to read all processes from my computer in Bash and then put them in a log file. However, when I run the code below, each individual string is added to the array instead of the full line.

processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]}

This is the result that I get PID COMM %MEM %CPU 538 /usr/sbin/distno 0.0 0.0 539 /usr/sbin/cfpref 0.1 0.0 556 /usr/libexec/Use 0.2 0.0 559 /usr/sbin/univer 0.2 0.0 560 /usr/libexec/kno 0.3 0.0 561 /System/Library/ 0.2 0.0

How can I modify this code so that processes is an array of lines instead of strings?

PID COMM %MEM %CPU
538 /usr/sbin/distno 0.0 0.0
539 /usr/sbin/cfpref 0.1 0.0
556 /usr/libexec/Use 0.2 0.0
559 /usr/sbin/univer 0.2 0.0
560 /usr/libexec/kno 0.3 0.0
561 /System/Library/ 0.2 0.0

I want to read the entire process line into array instead of each string individually

Karl
  • 1
  • 1

2 Answers2

2

Use readarray (in bash):

readarray -t p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"

edit (for bash < 4)

IFS=$'\n' read -r -d '' -a p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
-1

Do as follow:

processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]} | awk '{ for(i=1;i<NF;i++)if(i%4==0){$i=$i"\n"} }1'
Mairon
  • 621
  • 8
  • 21