__pgrepf()

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(): //www.ronggeng.net/index.php/2009/04/24/basename/
# dirname(): //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;
}

emptydir()

# emptydir() -- return true if directory empty
# Usage: emptydir directory
#
# Example:
#
# if ! emptydir /tmp; do
#  echo "/tmp not empty";
#done
#

emptydir() {
        local _dir="$1" _d;
        [ ! -d "$_dir" ] && return 2;
        for _d in $_dir/* $_dir/.*; do
                [ "$_d" = "$_dir/." ] || [ "$_d" = "$_dir/.." ] && continue;
                [ -e "$_d" ] && return 1;
        done;
        return 0;
}