user8544907
user8544907

Reputation:

Bash pgrep regexp function

I want to create a bash script which would check if the foo is already running and to run it if it's not.

Here is the code:

#!/usr/bin/env bash

function run {
 if ! pgrep $1;
 then
  $@
 fi
}
run foo

After executing the script it starts another instance of foo despite foo is already running.

pgrep foo returns process number so i can make the script kill it first and then start foo again but i want to know if this can be done as described on top. What am i missing here?

Upvotes: 0

Views: 850

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

A few improvements:

function run {
    if ! pgrep -x "$1" >/dev/null
    then
        "$@"
    fi
}
run foo bar "baz qux"

notes:

  1. quote all your variables. That will maintain any words containing whitespace.
  2. redirect the output from pgrep
  3. use the -x pgrep option to restrict the search for processes named "foo", as opposed to processes containing "foo"

You can shorten this to

run() { ! pgrep -x "$1" >/dev/null && "$@"; }

We could write pgrep -x "$1" >/dev/null || "$@" but that will return a successful exit status if the process is already running, and I think it makes more sense to return a failure status if the process cannot be launched.

Upvotes: 1

Related Questions