Hello
I want to allow only one instance of shell to execute but with one particular command line argument
Thus if the same shell script is executing with another command line argument it shall be be allowed
Ex.
while following is executing
Code:
./outer.sh argument_1
This shall not be allowed
Code:
./outer.sh argument_1
However folowing shall be allowed
Code:
./outer.sh argument_2
AS of now I have got it worked by following methods [1] & [2]; But I want to achieve it using method [3], which is not working for me
[1]
Here I am checking-inserting-deleting the 'command line argument' in a file(say flag or lock file)
However I am looking for better option rather than depending on file external file to control this
Code:
#!/bin/bash
arg=$1
grep ${arg} /tmp/arg.txt
if [ $? -eq 0 ]; then
echo "another instance of the script is already running"
exit
if [ $(pidof -x outer.sh| wc -w) -gt 2 ]; then
echo "another instance of the script is already running"
exit
fi
fi
echo ${arg} >> /tmp/arg.txt
while read p; do
sleep 60
/tmp/inner.sh $p
done < $1
sed -i "/$arg/d" z.txt
[2]
Code:
#!/bin/bash
scriptname=`basename $0`
#if [ `ps -ef|grep ${scriptname}|grep "log1.txt"|awk '{print $2}'|wc -l` -gt 2 ]; then
if [ `ps -ef|grep ${scriptname}|grep ${1}|awk '{print $2}'|wc -l` -gt 2 ]; then
echo "another instance of the script is already running"
exit
fi
while read p; do
sleep 60
/tmp/inner.sh $p
done < $1
[3]
The following works only when the "command line argument" is hardcoded in the shell script but not as a variable
Hardcoding the command line argument of inner script in calling i.e. outer script works (as below)
Code:
cat outer.sh
#!/bin/bash
scriptname=`basename $0`
pidfile=/tmp/${scriptname}.pid
if [ -f ${pidfile} ]; then
OLDPID=`cat ${pidfile}`
# here the command line argument "log1.txt" is hardcoded
RESULT=`ps -ef | grep ${OLDPID} | grep ${scriptname} | grep "log1.txt"`
if [ -n "${RESULT}" ]; then
echo "another instance of the script is already running"
exit 255
fi
fi
PID=`ps -ef | grep ${scriptname} | head -n1 | awk ' {print $2;} '`
echo ${PID} > ${pidfile}
while read p; do
sleep 60
/tmp/inner.sh $p
done < $1
if [ -f ${pidfile} ]; then
rm ${pidfile}
fi
Please suggest
Thanks in Advance
Kind Regards
Karan