0

I'm pretty new to bash and I'm trying to find the process with odd pid and biggest memory usage, so I came up with:

maxpid=0; maxsize=0; ps -axl --no-headers | tr -s ' ' : | cut -d : -f 3,8 | while read proc; do pid=$((echo $proc | cut -d : -f 1)); psize=$((echo $proc | cut -d : -f 2));if(($pid % 2 == 1)); then if(($psize > $maxsize)); then maxsize=$psize; maxpid=$pid; fi; fi; done; echo "$maxpid $maxsize";

Which, with a bit of indentation, is:

maxpid=0; maxsize=0; 
ps -axl --no-headers | tr -s ' ' : | cut -d : -f 3,8 | 
while read proc; do                              (1)
    pid=$((echo $proc | cut -d : -f 1));         (2)
    psize=$((echo $proc | cut -d : -f 2));       (3)
    if(($pid % 2 == 1); then 
        if($psize > $maxsize); then 
            maxsize=$psize; 
            maxpid=$pid; 
        fi; 
    fi; 
done; 
echo "$maxpid $maxsize";

I need to run it from command line, so I don't want a bash script. I know the two nested if are not so good, but I wasn't able to use logical AND.. I tried:

if(($pid % 2 -eq 1 -a $psize -gt $maxsize)); then

and also

if(($pid % 2 == 1 && $psize > $maxsize)); then

I also tried square brakets, but I'm not able to get it to work. Any help and correction are widely appreciated.

EDIT: I was able to shorten rows (1), (2) and (3) into

while read -r pid psize; do

EDIT 2: with a little more debug, I was able to see that everything is working correctly inside the if body (which I corrected to if (($pid % 2 ==1)) && (($psize > $maxsize)); then, the vars maxpid and maxsize are correctly set, but then the last echo is printing "0 0".. Looks like I have a problem of synchronization

Yuri
  • 3,082
  • 3
  • 28
  • 47
  • 1
    Your `while` loop is beeing executed in a child process due to pipes. Therefore, the changes of the environment of that child process, such as changes in the values of its variables `pid` and `psize`, are lost when the loop ends (`end` keyword). Read the last paragrahp in the section [**pipelines**](https://tiswww.case.edu/php/chet/bash/bashref.html#Pipelines) of man manual pages – Jdamian Jan 07 '17 at 17:01
  • What can I add to make it work? – Yuri Jan 07 '17 at 17:03
  • 1
    This is a classical problem. Read the following [solved question](http://stackoverflow.com/questions/4667509/problem-accessing-a-global-variable-from-within-a-while-loop/4667725#4667725). I guess there must be many questions in this website about this issue. – Jdamian Jan 07 '17 at 17:08
  • easiest way to get info from loop out is echo it (or save to file or somethin similarly boring) – MacHala Jan 07 '17 at 17:11
  • Thank you @Jdamian – Yuri Jan 07 '17 at 17:16

0 Answers0