0

I want to know from within the script if that script already running. A regular look on ps won't cut it as it get's different arguments in different order..

So the function should do:

check_already_running(){
    if [ `ps -ef| grep $script_name_with_arguments | wc -l ` -gt 1 ]
    then
      echo "already running"
      exit 1
    else
      echo "ok"
    fi
}

For example let's assume I ran ./test.sh -a 2 -c 4, so:

server:/tmp >./test.sh
ok
server:/tmp >./test.sh -a
ok
server:/tmp >./test.sh -a 2 -c 4
already running
server:/tmp >./test.sh -a 2   -c 4
already running
server:/tmp >./test.sh -c 4 -a 2
already running

I'm guessing the last 2 examples makes it a lot harder and longer to check, so if you can provide 2 options - one that's enough for exact command running and the other one if the user sent the same arguments but with different order/extra spacing.

Nir
  • 1,335
  • Create à temp file you delete When your script ends. This is the easier way – Kiwy Nov 06 '18 at 08:53
  • Can be problematic if server crashes, or script killed by kill -9 or ctrl+c – Nir Nov 06 '18 at 08:56
  • @Kiwy It doesn't look like the question you point to includes checking for the whole command line. pgrep allows for it with -f, but as far as I can tell it doesn't consider same arguments in different order as the same command line (with good reason, since differently ordered command lines can well differ in meaning). And it seems the OP is asking for it. – fra-san Nov 06 '18 at 10:39
  • Exact comparison of command lines is as easy as diff <(cat /proc/current_pid/cmdline) <(cat /proc/existing_pid/cmdline). Spacing should not be an issue: if unquoted, they are removed when the command line is interpreted. Comparing command lines with differently sorted arguments may be done only knowing how they are parsed by your script (mixed options and arguments, mixed - and --, spaces and equal signs, handling of repeated options...). – fra-san Nov 06 '18 at 11:01

0 Answers0