Search code examples
linuxbashshellunixps

Trying to join output from ps and pwdx linux commands


I am trying to join output from ps and pwdx command. Can anyone point out the mistake in my command.

ps -eo %p,%c,%u,%a --no-headers | awk -F',' '{ for(i=1;i<=NF;i++) {printf $i", 
"} ; printf pwdx $1; printf "\n" }'

I expect the last column in each row to be the process directory. But it just shows the value of $1 instead of the command output pwdx $1

This is my output sample (1 row):

163957, processA , userA , /bin/processA -args, 163957

I expected

163957, processA , userA , /bin/processA -args, /app/processA

Can anyone point out what I may be missing


Solution

  • Try this:

    ps -eo %p,%c,%u,%a --no-headers | awk -F',' '{ printf "%s,", $0; "pwdx " $1 | getline; print gensub("^[0-9]*: *","","1",$0);}'
    

    Explanation:

    awk '{print pwdx $1}' will concatenate the awk variable pwdx (which is empty) and $1 (pid). So, effectively, you were getting only the pid at the output.

    In order to run a command and gets its output, you need to use this awk construct:

    awk '{"some command" | getline; do_something_with $0}'
    # After getline, the output will be present in $0.
    
    #For multiline output, use this:
    awk '{while ("some command" | getline){do_something_with $0}}'
    # Each individual line will be present in subsequent run of the while loop.