Score:-2

How to write a shell script for printing the PID and The owner and the Name of the Process using the Special Variable $$ as parameter for the skript

my flag

The script shall present the command pstree -hsup $$. I have tried many different ways but I couldn't find a way to print the output like this

28348 (bash,root)
28347 (su,root)
28346 (sudo,root)
14085 (bash,user)
14083 (lxterminal,user)
    1 (Systemd,root)
tm flag
Something like ``pstree -hsupA $$ | tr -d '\n' | sed 's/-[+-]-\| *[`|]-/\n/g'``? How should the output be sorted?
Flowless Man avatar
my flag
it should be sorted from the newest process to the oldest including the name of the owner and in the shell script i can't use the pstree command , i just want to printout the process from the current shell like (./shell.sh $$) it should print the processes and the PID and the the owner in this way PID (NAME,OWNER)
Score:2
tm flag

ps -o ppid will output the pid of the parent process. So, start with the current pid, and ask for the parent, then for its parent, and so on.

#! /bin/bash
pid=$1
while ((pid)) ; do
    ps -h -o 'pid,comm,euser' $pid \
        | sed -E 's/^( *[0-9]+ )([^ ]+) *([^ ]+)/\1(\2,\3)/'
    pid=$(ps -h -o ppid $pid)
done

You want to output pid, the command, and the effective user (or maybe real user?). Specify them in the -o and use sed to reformat the output. Here, we capture the three non-space strings and insert parentheses and a comma where needed.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.