Suppose the user of parent shell is foo
. If you run something like sudo -u bar -i
, then you are in a child shell with user bar
. So, how can I find out the user of the parent shell inside the child shell? Namely, in the case above, how can I know that the user of parent shell is foo
?
update
I understand that, with some hack, it is possible to achieve this using ps
. However, I would be much more interested in a less hacky and more standard way, if all possible.
update 2
With help from the answers, I finally resorted to the following solution:
# from parent shell, user is foo
$ sudo -u bar -i PARENT=foo
# from child shell, show parent user foo
$ ps u -p $PPID | grep PARENT | cut -d= -f2
You can use the
$PPID
variable to assist you along with a command or two:You can do a
ps -ef
and follow the list ofPPID
toPID
matches until you find the parent process you are interested in. For Linux,ps
usually gives the name of the process in the first column.For instance, I just typed
ps -ef
, and (ignoring the hundred or so lines before my command) get this (which is short enough that it should be clear):and with a
sudo
, vile is still the parent, but of a different chain of processes:Linux
ps
also has-H
and--forest
options which try to make the structure more readable (but the latter in particular defeats that by indenting too much).For example, here is a script which parses the output, and points out the places where a login shell occurs in the hierarchy. There is no standard for shell names, but login shells commonly are shown with a leading "-" in the
CMD
column:and output:
also tested with OSX (where the first column is a number):
First of all, bash has a nice builtin variable called
$PPID
, which holds the process ID of its parent process.Secondly,
/proc/<pid>/status | egrep '^Uid:' | awk '{ print $2 }'
can be used to obtain the user ID a process is running under.This means the following command will retieve the user ID of the direct parent process:
So, in the example of su, you need to go up two levels since su itself will already run under the new user. Hence the following command can be used to retrieve the user ID of the spawning process:
Note that
$PPID
may behave differently when used from within a stored bash-script.