pgrep대신 사용하십시오 :
pgrep -cxu $USER -f my-tool
사용되는 옵션은 다음과 같습니다.
-c, --count
Suppress normal output; instead print a count of matching pro‐
cesses. When count does not match anything, e.g. returns zero,
the command will return non-zero value.
-x, --exact
Only match processes whose names (or command line if -f is spec‐
ified) exactly match the pattern.
-u, --euid euid,...
Only match processes whose effective user ID is listed. Either
the numerical or symbolical value may be used.
이미 실행 중인지 확인하는 bash 스크립트에서 이것을 사용하려면을 사용할 수 있습니다 $0. 이것은 현재 스크립트 (예 :)의 경로로 확장 /home/username/bin/foo.sh되지만 필요합니다 foo.sh. 그것을 얻으려면, 우리는 마지막에 모든 것을 제거 할 수 있습니다 /사용 배쉬의 문자열 조작 도구 : ${0##*/}. 이것은 우리가 다음과 같은 것을 할 수 있음을 의미합니다.
## If there are more than 1 instances of the current script run
## by this user
if [[ $(pgrep -cxu "$USER" "${0##*/}") -gt 1 ]];
then
echo "Script already running, exiting."
exit
fi
이를 위해 잠금 파일 사용을 고려할 수도 있습니다.
## If the lock file exists
if [ -e /tmp/$USER.foo.lock ]; then
## Check if the PID in the lockfile is a running instance
## of foo.sh to guard against crashed scripts
if ps $(cat /tmp/$USER.foo.lock) | grep foo.sh >/dev/null; then
echo "Script foo.sh is already running, exiting"
exit
else
echo "Lockfile contains a stale PID, continuing"
rm /tmp/$USER.foo.lock
fi
fi
## Create the lockfile by printing the script's PID into it
echo $$ > /tmp/$USER.foo.lock
## Rest of the script here
## At the end, delete the lockfile
rm /tmp/$USER.foo.lock
pidof더 나은 도구가 거짓말이다pgrep