Bash: Evitando multiplas instâncias de um script

Alguns scripts não podem rodar multiplas instâncias, um caso clássico é o apt-get, caso ele rodasse mais de uma vez certamente teriamos quebra dos pacotes, para evitar isto usamos um script para evitar multiplas instâncias.
#!/bin/bash
# ------------------------------------------------------------
# File : AmIRunning
# Author : Jonathan Franzone
# Company : http://www.franzone.com
# Date : 09/23/2007
# Description : Test script for creating lock files
# source: http://www.franzone.com/2007/09/23/how-can-i-tell-if-my-bash-script-is-already-running/
# ------------------------------------------------------------
# ------------------------------------------------------------
# Setup Environment
# ------------------------------------------------------------
PDIR=${0%`basename $0`}
LCK_FILE=`basename $0`.lck
# ------------------------------------------------------------
# Am I Running
# ------------------------------------------------------------
if [ -f "${LCK_FILE}" ]; then
# The file exists so read the PID
# to see if it is still running
MYPID=`head -n 1 "${LCK_FILE}"`
TEST_RUNNING=`ps -p ${MYPID} | grep ${MYPID}`
if [ -z "${TEST_RUNNING}" ]; then
# The process is not running
# Echo current PID into lock file
echo "Not running"
echo $$ > "${LCK_FILE}"
else
echo "`basename $0` is already running [${MYPID}]"
exit 0
fi
else
echo "Not running"
echo $$ > "${LCK_FILE}"
fi
# ------------------------------------------------------------
# Do Something
# ------------------------------------------------------------
while true
do
clear
echo
ls -F
echo
date
echo
sleep 5
done
# ------------------------------------------------------------
# Cleanup
# ------------------------------------------------------------
rm -f "${LCK_FILE}"
# ------------------------------------------------------------
# Done
# ------------------------------------------------------------
exit 0
view raw lock_file.sh hosted with ❤ by GitHub

O artigo original que me inspirou foi este.

linux-cookbook

Grupos do Google
Participe do grupo linux-cookbook
E-mail:
Visitar este grupo