Search code examples
linuxshellunixprocfs

Correct way to detect '/proc' file system?


I'm writing a cross platform bash script. It needs to use this command #1:

cat /proc/$PID/cmdline

and if the procfs is not available (on OS X for example), it needs to fallback to this command #2:

ps -eo "pid command" | grep "^$PID"

My question is pretty simple: what is the correct way to detect if '/proc' file system exists?


Solution

  • The "proc filesystem" will almost always be mounted in /proc if present, but this does not have to be the case always (at least in theory). Probably a more portable way is to use mount -t proc to list mounted filesystems of type proc and extract the path from there. If the command returns no paths, procfs is not mounted and you can fall back to the alternative command.

    Something along the lines of:

    PROC_PATH=$(mount -t proc | egrep -o '/[^ ]+')
    if [ "$PROC_PATH" ]; then
        # use procfs
    else
        # use alternative
    fi
    

    On the other hand, ps should be more portable and always work, so maybe best solutions is just to use ps always?