如何检查一个shell脚本实例是否已经在运行 - Linux

时间:2021-06-14 16:24:27

I have two different shell script say like

我有两个不同的shell脚本说

a.sh 
b.sh

**code of a.sh**

#!/system/bin/sh
#some code
./xyz/b.sh &

Here we can see i am running b.sh through a.sh file which is postboot script. Each time when device gets reboot it is adding ./xyz/b.sh & which i am trying to avoid.

在这里,我们可以看到我通过a.sh文件运行b.sh,这是postboot脚本。每次设备重启时,都会添加./xyz/b.sh,我试图避免这种情况。

what i am trying to do : 
i need to write a code in such a way that will find if ./system/xyz/b.sh & is already there then no need to add again.



Code : 
if  pgrep /xyz/b.sh > /dev/null 2>&1
then
echo aplog is running
exit 1
fi

these code is not running. Do not know where i am doing mistake.

这些代码没有运行。不知道我在哪里做错了。

3 个解决方案

#1


0  

Just try:

pgrep b.sh > /dev/null 2>&1
if [ 0 == $? ]
then
...
fi

#2


0  

pgrep will only work on process name, not full path to process name.

pgrep仅适用于进程名称,而不是进程名称的完整路径。

Try pgrep -f b.sh or pgrep -x b.sh instead of pgrep -x /xyz/b.sh

试试pgrep -f b.sh或pgrep -x b.sh而不是pgrep -x /xyz/b.sh

#3


-1  

Hi test your file existence before creating it with:

您可以在创建文件之前测试您的文件:

filename="/fullpath/xyz/b.sh"
if [ -f "$filename" ]
then
        echo "$filename found"
else
        echo "$filename not found."
fi

#1


0  

Just try:

pgrep b.sh > /dev/null 2>&1
if [ 0 == $? ]
then
...
fi

#2


0  

pgrep will only work on process name, not full path to process name.

pgrep仅适用于进程名称,而不是进程名称的完整路径。

Try pgrep -f b.sh or pgrep -x b.sh instead of pgrep -x /xyz/b.sh

试试pgrep -f b.sh或pgrep -x b.sh而不是pgrep -x /xyz/b.sh

#3


-1  

Hi test your file existence before creating it with:

您可以在创建文件之前测试您的文件:

filename="/fullpath/xyz/b.sh"
if [ -f "$filename" ]
then
        echo "$filename found"
else
        echo "$filename not found."
fi