'"grep -v" weird behavior

I'm trying to make sure my script only runs once at a time, but im running into weird behavior with inverting grep.

My Code:

echo "Current Pid: $$"
# Output "Current Pid: 5387"
echo "Process Count: $(pgrep -c -f "$0")"
# Output: Process Count: 2

if [ "$(pgrep -c -f "$0")" -gt 1 ]
then
    echo All Pids
    pgrep -f "$0"
    # Output "4978, 5387"

    echo Pids Current
    echo "$(pgrep -f "$0" |& grep -F $$)"
    # Output "5387"

    echo Pids Inverted
    echo "$(pgrep -f "$0" |& grep -Fv $$)"
    # Output "4978, 5394"

    # processPidsToKill="$(pgrep -f "$0" |& grep -Fv $$)"

    # for processPid in $processPidsToKill; do
    #     echo "Killing `basename "$0"` $processPid"
    #     kill "$processPid"
    # done
fi

Can someone tell me what im doing wrong? Where does the new Pid come from when im using "grep -v"?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source