0

Hope you are having a good day.

The intention is to write the PIDs of some of the running processes into an array for further use.

Function()
{

    declare -a arr

    ps -e -o pid,%mem,command |

    awk -v val="$1" '{if($3 == val) print $1,$2,$3; $arr+=($1)}'
}

It seems I can't have access to arrays/variables inside awk.

I'd appreciate any help!

Francesco
  • 897
  • 8
  • 22
  • awk is a totally different tool+language to shell. See https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – Ed Morton May 15 '20 at 19:28

1 Answers1

1

The Bash array arr is not accessible inside of awk, or even outside of the function. It looks like you're filtering specific commands in the ps output. So let's simplify this as:

declare -a arr=( $(ps -e -o pid,%mem,command | grep "$1\$" | tee /tmp/pid$$ | cut -c-5) )
printf '%s\n' "${arr[@]}"
cat /tmp/pid$$
  • This assigns values to the array in the declaration.
  • The array values are taken from the output from the ps/grep/cut commands.
  • The argument to grep looks for "any line that ends with $1".
  • The cut is just taking the first argument, which is the PID of each process.
  • The tee sends the intermediate output to a file for printing (optional).
  • The printf meets your "further use" requirement.
Eric Bolinger
  • 2,722
  • 1
  • 13
  • 22
  • Thanks, Such a great solution. I was just wondering if it could be achieved by awk? Because my actual condition is more complex and my bash knowledge is not enough to rewrite your expression. Mind if I edit the solution with the actual condition? also I guess it's good to mention that my future use is simply killing the processes upon the user request. – HelpSeeker May 15 '20 at 18:33
  • 1
    In that case... you must use array indexes. Something like this AWK script: `{ if ($3 == val) { print $1,$3; arr[i++]=$1 } }; END {for (v in arr) print "pid " arr[v]}`. – Eric Bolinger May 15 '20 at 20:13