How to get the absolute path of a script using its PPID - Bash

273 views Asked by At

I am trying the absolute path of a given PPID from a shell script. However, the Parent Process may be any type of script (bash/csh/zsh/tsh/Makefile).

The child process is always a bash script and is the only script I have access on to edit.

I have tried:

  1. ps --no-headers -o command $PPID but it only gets the command that invoked the parent process. This isn't what I need because the parent may have caused some cd's inside the script and I won't be able to resolve the relative path in the command to it.

  2. ls -l /proc/$PPID/fd/255 and this was the closest to what I want but this is specific to bash scripts and as I mentioned, I don't have access to know my parent process' script type.

  3. /proc/$PPID/exe returns the binary exe, and I need the script's absolute path that is using this binary.

1

There are 1 answers

2
chrslg On
  • There isn't such thing as "the" absolute path. There may be several way to access the same file. And some times, none of them (or more than one of them, depends how you look at it) are "the" main name. I am thinking of hard links here, for example.

  • Makefile is never the path of a script. It is just a configuration file. That is read by default by the executable. Which is probably /usr/bin/make. To find a path to the Makefile file, you need to read arguments of make. Or to find a Makefile among open files (assuming there is only one, and that it is named Makefile, and that is not certain). And the strategy to guess what is the Makefile of a make process is specific to make. You need another strategy to guess what is the script file executed by a bash process, Another to find what is the python file executed by a python command (which could be a shebang python "executable", a python ../somerealtive/path/somefile.py a python /some/absolute/paht a python -m somemodele, a python -c "import somemod ; somemod.run()" etc.)

  • Now, since you've mentioned /proc/$PPID/exe, you can get the file "pointed" by this, using path=$(readlink -f /proc/$PPID/exe)

Again, that is linux solution, more than a bash one. You have no guarantee from bash that the system on which you run this command have a /proc filesystem

I must add that I suspect a XY problem here. What are you trying to do exactly?