LoginSignup
36

More than 5 years have passed since last update.

Bashで二重起動防止

Posted at

いちいちlockファイル置いたりしてexitしたらゴミが残ったり、シビアなタイミングだとファイル作る前に2つ目が起動しちゃったりするのはナンセンス。

お手軽かつ比較的正確にやるなら、pgrepで既に同じシェルが起動していないか調べれば良い。

if [ $$ -ne $(pgrep -fo "$0") ]; then
  echo "既に起動されています"
  exit 1
fi

引数も含めて多重をチェックするなら、検索する文字列を少し工夫する。

_CMD="$0 $@"
if [ $$ -ne $(pgrep -fo "$_CMD") ]; then
  echo "既に起動されています"
  exit 1
fi

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36