Use LOCK em Bash script

De Wiki Hackstore

LOCK usando if + ps

Script de exemplo:

#!/bin/bash

###############################################################################
# Testa se script já encontra-se em execução

test_running() {
        RUNNING=$(ps aux | grep "$(printf '%s\n' "${0##*/}")" | grep bash | grep -v "bash -c" | grep -v $$ | grep -v grep | wc -l)
        if [ ${RUNNING} -gt 1 ]; then
                echo "Script ja esta rodando, aguardando 10 segundos para tentar novamente."
                sleep 10
                RUNNING=$(ps aux | grep "$(printf '%s\n' "${0##*/}")" | grep bash | grep -v "bash -c" | grep -v $$ | grep -v grep | wc -l)
                if [ ${RUNNING} -gt 1 ]; then
                        echo "Script ja esta rodando, nao sera executado novamente."
                        exit 1
                fi
        fi
}

test_running
###############################################################################
# Iniciando script

sleep 30

###############################################################################
# Fim do script

Lock de kernel usando FLOCK =

Crie lock para executar seus scripts bash, no caso exemplificado, o script exec.sh:

#!/bin/bash

data_hora() {
echo "[$(date +'%Y/%m/%d') $(date +'%H:%M:%S')]"
}

# Criando LOCK do script....
LOCK="teste.lock"
{
if ! flock -n 200; then
        echo -e "$(data_hora) Script rodando.... saindo imediatamente.\n"
        exit 1
else
        sh exec.sh
fi
} 200>${LOCK}

# Removendo arquivo de LOCK...
rm $LOCK

# Fim


Caso deseje incorporar o lock flock em algum script existente, basta colocar o script dentre de um IF:

Ex:

Início de script:

#!/bin/bash

data_hora() {
	echo "[$(date +'%Y/%m/%d') $(date +'%H:%M:%S')]"
}

# Criando LOCK do script....
LOCK="/backup/backup-lns.lock"
{
if ! flock -n 200; then
	echo -e "$(data_hora) Script rodando.... saindo imediatamente.\n"
	exit 1
else
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala
	script antigo lalalala

Fim do script:

fi
} 200>${LOCK}

# Removendo arquivo de LOCK...
rm $LOCK

Dúvidas, man flock :D


Referências:

http://linux.die.net/man/1/flock
http://unixhelp.ed.ac.uk/CGI/man-cgi?flock