既に動いているか確認してからコマンドを実行する1行シェルスクリプト

既に動いているか確認してからコマンドを実行する1行シェルスクリプト

ps ax | grep [c]ommand | grep [a]rgv1 | grep [a]rgv2 | wc -l

0 動いていない
1 1つ動いている

動いていない事を確認したら実行する

if [ $(ps ax | grep [c]ommand | grep [a]rgv1 | grep [a]rgv2 | wc -l) == 0] ; then command -argv1 -argv2 ; fi;

cronを動かす際に、2回目の実行前に前に実行したコマンドが終了していない時なんかに便利。

ちなみに、APIを叩いて状況を確認した上でコマンドが終了していないか確認する方法は

if [ $(curl -s http://localhost/api/api.json) == '[]' ] && [ $(ps ax | grep [c]ommand | grep [a]rgv1 | grep [a]rgv2 | wc -l) == 0 ] ; command -argv1 -argv2 ; fi;

整形するとこんな感じ

if
  [ $(curl -s http://localhost/api/api.json) == '[]' ] &&
  [ $(ps ax | grep [c]ommand | grep [a]rgv1 | grep [a]rgv2 | wc -l) == 0 ] ;
  then
    command -argv1 -argv2 ;
fi;