Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read input from the stdout of another command (pipe) in linux shell script?

My objective is to find the process that is consuming the most CPU and RAM by writing a script. I've managed to extract the info from TOP command however, I'm having trouble parsing the output.

The following command,

top -b -n 1 | tail -n +8 | head -n 1

Will output something similar to this single line,

915 root      20   0  209m  74m 8644 S    8  7.7   5:27.57 Xorg

I want this line of text to be the argument list for my script. I realize that I have to read it from the STDIN but, I want to read the above output word by word, or argument by argument as if it was given from the command line.

echo " Parameter is ${2} ${3}"
like image 510
Vivek Bernard Avatar asked Dec 13 '25 19:12

Vivek Bernard


2 Answers

Use set -- to force the arguments to become positional parameters.

set -- $(top -b -n 1 | tail -n +8 | head -n 1)
echo " Parameter is ${2} ${3}"
like image 142
glenn jackman Avatar answered Dec 15 '25 11:12

glenn jackman


Just for fun :)

top -b -n1 | head -8 | tail -2 | awk '
{
    if (NR==1) {
        print "\nHey teacher, leave those kids alone! - Pink Floyd ;)\n";
        print $2,$1,$9,$10;
        next;
    }
    print $2,$1,$9,$10;
}'

Or if you want another report format:

top -b -n1 | head -8 | tail -1 | awk '{ printf "User: %s\nPID: %s\nCPU Usage: %s\nMEM Usage: %s\n", $2,$1,$9,$10 }'
like image 22
jyz Avatar answered Dec 15 '25 09:12

jyz