I need to use awk to see what users are logged in the computer, create a file with their names and inside that file print the pid of the process they're running. I've used this, but it does not work:
who | awk '{for(i = 0; i < NR; i++)
system("ps -u " $1 "| tail +2 | awk '{print $1}' >" $1".log")
}'
Is there any way to do this?
Thanks a lot!
To achieve your goal of using awk
to create those files, I would start with ps
rather than with who
. That way, ps
does more of the work so that awk
can do less. Here is an example that might work for you. (No guarantees, obviously!)
ps aux | awk 'NR>1 {system("echo " $2 " >> " $1 ".txt")}'
Discussion:
The command ps aux
prints a table describing each active process, one line at a time. The first column of each line contains the name of the process's user, the second column its PID. The line also contains lots of other information, which you can play with as you improve your script. That's what you pipe into awk
. (All this is true for Linux and the BSDs. In Cygwin, the format is different.)
Inside awk
, the pattern NR>1
gets rid of the first line of the output, which contains the table headers. This line is useless for the files you want awk
to generate.
For all other lines in the output of ps aux
, awk
adds the PID of the current process (ie, $2
) to the file username.txt
, using $1
for username
. Because we append with >>
rather than overwriting with >
, all PIDs run by the user username
end up being listed, one line at a time, in the file username.txt
.
UPDATE (Alternative for when who
is mandatory)
If using who
is mandatory, as noted in a comment to the original post, I would use awk
to strip needless lines and columns from the output of who
and ps
.
for user in $(who | awk 'NR>1 {print $1}')
do
ps -u "$user" | awk 'NR>1' > "$user".txt
done
For readers who wonder what the double-quotes around $user
are about : Those serve to guard against globbing (if $user
contains asterisks (*
)) and word splitting (if $user
contains whitespace).
I will leave my original answer stand for the benefit of any readers with more freedom to choose the tools for their job.
Is that what you had in mind?