use*_*216 4 scripting process shell-script
linux中是否有脚本或方法可以在我尝试执行shell脚本/进程时,如果它正在运行,它会提示它正在运行并退出,否则它将继续。
您可以使用这个衬垫来做您想做的事:
$ pgrep script.bash && echo "already running" || ( ./script.bash & )
Run Code Online (Sandbox Code Playgroud)
假设我有这个脚本:
$ cat script.bash
#!/bin/bash
echo "Hello World"
sleep 10
Run Code Online (Sandbox Code Playgroud)
如果我们使用我们的一个班轮:
$ pgrep script.bash && echo "already running" || ( ./script.bash & )
Hello World
$
Run Code Online (Sandbox Code Playgroud)
我们再次运行它:
$ pgrep script.bash && echo "already running" || ( ./script.bash & )
10197
already running
$
Run Code Online (Sandbox Code Playgroud)
等待 10 秒并再次运行它,它再次起作用:
$ pgrep script.bash && echo "already running" || ( ./script.bash & )
Hello World
$
Run Code Online (Sandbox Code Playgroud)
请注意,此答案面向自检查脚本,用于在尝试从命令行运行进程之前手动检查进程是否正在运行,请参阅slm 的答案。
最简单的方法是在pgrep
可用时使用:
if pgrep "$0" >/dev/null
then
echo "$0 is already running" 2>&1
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
如果没有,你可以使用的组合ps
和grep
:
if ps -Ao comm | grep -q "^$0\$"
then
echo "$0 is already running" 2>&1
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
使用锁定文件更健壮,因为进程总是可能以不同的名称运行。这是一个使用示例flock
:
lockfile=/var/lock/mprog
{
if ! flock -n 9
then
echo "Unable to lock $lockfile, exiting" 2>&1
exit 1
fi
# do stuff here
} 9>"$lockfile"
Run Code Online (Sandbox Code Playgroud)