Created
April 26, 2016 16:56
-
-
Save algal/d291544cc8845da15c93b8d4a5a9224e to your computer and use it in GitHub Desktop.
Check if the current process has a given ancestor by name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# works on plain vanillla OS X 10.11.4 without installing pstree, | |
# which is of course the sane way to do this | |
if [ "$#" -ne 1 ]; then | |
echo "usage: $0 key" 1>&2 | |
echo "$0 finishes with an exit code of 0 if key was found in ancestral process; 1 if not; 2, if it is showing this usage message" 1>&2 | |
exit 2 | |
fi | |
key="$1" | |
function join { local IFS="$1"; shift; echo "$*"; } | |
function parentProcess() { | |
ps -p "$1" -o ppid= | |
} | |
foundPids=() | |
currentPid="$$" | |
while [ $(parentProcess "$currentPid") != "0" ]; do | |
foundPids+=" $(parentProcess "$currentPid") " | |
currentPid=$(parentProcess "$currentPid") | |
done | |
exec fgrep "$key" <(ps -p "$(join , "$foundPids")") >/dev/null 2>/dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment