1

I want something like this:

maybeexec command arg1 arg2 &> /logs/log

Where maybeexec is a bash function, like so:

maybeexec() {
  if ! ps ax | grep -v grep | grep "$*" > /dev/null
  then
    "$@"
  fi
}

So basically it checks if command arg1 arg2 is already running, and if so, does not run it.

My problem, though, is that even if command arg1 arg2 is already running and so maybeexec does not run it concurrently, /logs/log is still opened for redirection and will overwrite the existing /logs/log, which I do not want.

What's the most elegant way to solve this? If possible, I'd like to keep calling maybeexec as I do now, since I use it to run many commands that all redirect output to different files.

Thanks!

2 Answers 2

1

You need to rewrite your code a little bit. Make redirection inside the function, not outside. The target for the redirection is noe specified as the first argument of the function (later it will be removed with shift):

maybeexec /logs/log command arg1 arg2

maybeexec() {
  LOG=$1
  shift
  if ! ps ax | grep -v grep | grep "$*" > /dev/null
  then
    "$@" >& $LOG
  fi
}
Sign up to request clarification or add additional context in comments.

Comments

1

I don't understand what your function is trying to do or what your issue is with redirection. The file descriptor table cannot be modified externally after a process is started (except with GDB and other hacks).

Please use proper process management instead of ps in scripts. This approach isn't good. To search for a process by name, you should use pgrep, but that should never be done in a script either.

See also: http://wiki.bash-hackers.org/howto/mutex and: http://mywiki.wooledge.org/BashFAQ/045

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.