Search code examples
linuxbashlinux-kernelprocfs

Linux: Reading the output of readlink /proc/pid/exe within a Bash Script


So I am writing a bash script which will run through all of the process ids in /proc/[pid] and read the executable that was used to run it.

From what I have had a looked at, the /proc filesystem contains the /proc/[pid]/exe symbolic link. Within the bash script I am trying work out how to read the value of "readlink /proc/[pid]/exe" to check if (deleted) or nothing is returned to find out whether the original executable exists on the disk or not.

Is there a way of doing this, so far I have?

#!/bin/bash
pid = "0"

while [ $pid -lt 32769 ]
do
    if [-d /proc/$pid]; then
        if [-f /proc/$pid/exe]; then
            echo $pid
            readlink /proc/$pid/exe
        fi
    fi
    pid = $[$pid+1]
done

This fails to work and always returns nothing.I am trying to list all of the processes that no longer have their executables available on disk.


Solution

  • Will this work for you?

    #!/bin/bash
    
    for i in $(ls /proc | awk '/^[[:digit:]]+/{print $1}'); do
      if [ -h /proc/$i/exe ]; then
        echo -n "$i: "
        if readlink /proc/$i/exe >/dev/null 2>&1 ; then
          echo "executable exists"
        else
          echo "executable not found"
        fi
      fi
    done