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