This function implementing “pgrep -f” command in pure bash. In term of performance wise, a little bit slow than “pgrep -f”.
# __pgrepf() -- get pid match program from /proc # Usage: __pgrepf [name] # alternative depend: basename(): http://www.ronggeng.net/index.php/2009/04/24/basename/ # dirname(): http://www.ronggeng.net/index.php/2009/04/24/dirname/ # # Example: # # if ! __pgrepf httpd; then # /etc/init.d/httpd restart # fi # __pgrepf() { [ -n "$1" ] && [ -d "/proc" ] || return 1; local _mt="$1" _buf _f _pid _pidr="" _me=$$; _mt=${_mt// /}; for _f in /proc/*/cmdline; do _pid=$(basename $(dirname $_f)); ! [[ $_pid =~ ^([0-9]+)$ ]] && continue; (( $_pid < = 9 )) && continue; [ "$_pid" = "$_me" ] && continue; _buf=$(< $_f); [ -z "$_buf" ] && continue; [[ $_buf = *$_mt* ]] && _pidr+="$_pid "; unset _pid _buf; done; [ -n "$_pidr" ] && { echo "$_pidr"; return 0; }; return 1; }