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

My goal is to find a process that consumes most CPU and RAM by writing a script. However, I managed to extract information from the TOP command, but I had problems parsing the output.

Next command

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

Print 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 a list of arguments for my script. I understand that I need to read it from STDIN, but I want to read the above output word by word or argument by argument, as if it were specified from the command line.

echo " Parameter is ${2} ${3}"
+3
source share
5 answers

Get string in variable:

OUTPUT=`top -b -n 1 | tail -n +8 | head -n 1`

Convert to Array:

LIST=($OUTPUT)

And print the fields:

echo ${LIST[1]}
echo ${LIST[2]}
+1

set --, .

set -- $(top -b -n 1 | tail -n +8 | head -n 1)
echo " Parameter is ${2} ${3}"
+2

:)

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;
}'

, :

top -b -n1 | head -8 | tail -1 | awk '{ printf "User: %s\nPID: %s\nCPU Usage: %s\nMEM Usage: %s\n", $2,$1,$9,$10 }'
+2

, :

LINE=$(top -b -n 1 | tail -n +8 | head -n 1 | tr -s ' ')

cut, :

echo " Parameter is $(echo $LINE | cut -d' ' -f2) $(echo $LINE | cut -d' ' -f3)"

...

, , ,

+1

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

:

top -b -n 1 | tail -n +8 | head -n 1 |
    read XPID XUSERID XPRIORITY XVIRTUAL XRESIDENT XSHARED XSTATE XCPU XMEM XTIME XCOMMAND

( , , ... - , )

+1

Source: https://habr.com/ru/post/1762930/


All Articles