我有一个bash脚本,该脚本执行一系列命令来修改文件系统上的文件。我想在运行这些命令的同时运行后台进程,以便在另一个实例已经运行时无法调用我的bash脚本。
几乎类似以下内容:
#!/bin/bash
if pgrep mystery_background_cmd; then
echo 'The file is being modified right now. Exiting.'
fi
<script commands here>
bg_pid="$( mystery_background_cmd & echo "${!}" )"
<do other commands here>
kill "${bg_pid}"
因此,实际上:
$ ./script.sh &
Modifying files...
$ ./script.sh &
The file is being modified right now. Exiting.
或者更好的是,像这样:
$ ./script.sh &
Modifying files... # 1st instance
$ ./script.sh &
The file is being modified right now. Seconds until re-check: {5..1} # 2nd instance
The file is being modified right now. Seconds until re-check: {5..1} # 2nd instance
Finished modifying! # 1st instance
Modifying files... # 2nd instance
我正在使用bash 3.2.57(1)-release和macOS High Sierra 10.13.6。