A
A
Anatoly2019-01-20 19:10:55
linux
Anatoly, 2019-01-20 19:10:55

How to make a bash script terminate if another program is already running?

There are 2 bash files, the first one is launched by the scheduler on an event, and has the code:

#!/bin/bash
#
# Проверяем запущен ли уже скрипт, если да, то выход
[ `pgrep -c optimize.sh` -gt 1 ] && echo "Программа уже запущена" >> /var/www/oo.log  && exit 1
# Если не запущен - запускаем
/var/www/optimize.sh

The first script should run the second script if it is not running. How to terminate the first script if the second script is already running?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly, 2019-01-21
@Tolly

I close the question, the problem was that the second script was launched sequentially, and until it was executed, no other actions took place, so exit did not work, for the same reason there was not more than one "Passed .." in the logs.
The solution is: launch the script is not sequential, but in the background, then control is transferred to the next command, and do whatever you like ..
The script should have been run as: optimize.sh &

A
Alexander, 2019-01-21
@UPSA

Why don't you use ps?
if ps aux | grep optimize.sh ; then echo "RUNNING!!!" ; fi
as non-pros can be wrong in the syntax)))

P
planc, 2019-01-21
@planc

1.sh:

#!/bin/bash

if PID=`pgrep -x "myproc.sh"`
then
    echo "уже запущен $PID"
else
    echo "запускаю"
    ./myproc.sh &
fi

myproc.sh:
#!/bin/bash

echo "запускаю процесс $$"
sleep 10
echo "завершился процесс $$"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question