Terkadang kita ingin hanya satu saja (maksimal) script bash yang kita buat yang berjalan. Misalnya dalam keperluan rsync, tentunya kita tidak ingin ada banyak instance berjalan, karena jelas menyedot bandwidth dan CPU yang tinggi. Bagaimana caranya bisa begitu? Caranya tandai saja setiap proses yang berjalan dengan membuat file PID (process ID). Kalau process tersebut masih ada, maka exit script yg baru. Jika sudah mati, barulah boleh jalankan instance baru.
Misalnya, kita hanya ingin ada satu instance script rsyncstatic.sh yang berjalan, maka lakukan seperti ini
#! /bin/bash
mypidfile="rsyncstatic.sh.pid"
# Check if file exists, which means other instance is running
if [ -f $mypidfile ]; then
echo "$mypidfile exists, exiting ..."
exit 1
fi
# Create a file with current PID to indicate that process is running.
echo $$ > "$mypidfile"
# Ensure PID file is removed on program exit.
trap "rm -f -- '$mypidfile'" EXIT
# Begin rsync
echo "Begin Rsync"
rsync -azv --delete --ignore-errors user@remote:public_html/ ~/home/username/public_html
Menyeleksi via Proses
Cara lain yang bisa dilakukan adalah melakukan seleksi via proses, jadi misalnya ada proses tertentu yg kita ingin hanya ada satu instance, kita seleksi pakai pgrep:
# Check if other process is running
thisuser=$USER
processname=""
if pgrep -u $thisuser $processname >/dev/null;
then
echo "Exiting, ... other $processname by $thisuser is running, ..."
exit 1
fi
Bisa juga kita seleksi berdasar nama script yang berjalan, misalkan:
# Check if other scripts is running
thisuser=$USER
scriptname="NamaScript.sh"
scriptcount=$(pgrep -u $thisuser -f $scriptname | wc -l)
if test $scriptcount -gt 1
then
echo "Exiting, ... other $scriptname by $thisuser is running ($scriptcount instances), ..."
exit 1
fi
Leave a Reply