Search code examples
bashprocessgrep

How to use pgrep with slash?


I want to make the following bash code working:

#!/bin/bash

SERVICE="/usr/sbin/some_command"
if pgrep -x "$SERVICE" >/dev/null; then
  echo "$SERVICE is already running"
else
  $SERVICE some_arguments
fi

I think the slash / causes some trouble but I still want to keep it.


Solution

  • On Linux you need to use -f to match the whole command line because without it pgrep just looks in the process name which contains no / and has maximum 15 characters

    SERVICE="/usr/sbin/some_command"
    if pgrep -f "$SERVICE" >/dev/null; then
      echo "$SERVICE is already running"
    else
      $SERVICE some_arguments
    fi
    

    However be aware that the command line may not contains the full path at all because it's possible to exec a file with $0 being empty, so in such cases you won't get the desired output

    From man pgrep:

    • -f, --full
      • The pattern is normally only matched against the process name. When -f is set, the full command line is used.

    ...

    Notes:

    The process name used for matching is limited to the 15 characters present in the output of /proc/pid/stat. Usethe -f option to match against the complete command line, /proc/pid/cmdline.