シェルスクリプトはファイルから複数のパターンを検索し、そのパターンと3つ以上の条件を一致させます。

シェルスクリプトはファイルから複数のパターンを検索し、そのパターンと3つ以上の条件を一致させます。

いくつかの条件を実行しましたが、ファイル内の3つ以上の条件を確認するための正確な構文を取得できませんでした。

ファイルで複数のgrepを実行できますが、条件付きの3つのパターンを追加することはできません。以下の通りです。

CASE/Loop/if-else(はしご構文)を提供できます。私は、ユーザーがこのスクリプトを実行したときにユーザーフレンドリーなメッセージを印刷したいだけです。 start.logファイル内のパターンの代わりに、これらのユーザーフレンドリーなメッセージは、Startup.logでどのパターンが見つかるかによって異なります。

start.logで上記のコマンドを実行したときにpidがすでに存在することを発見し、次のようにecho "DB servicesすでに実行中"を印刷したいとします。

pg_ctl -D $PGDATA start > startup.log

if [$? -eq 0]

then
#if db services is stopped priviously, then it will start and grep below msg to user 
ls -t postgresql*.log | head -n1 | args grep "Database for read only connections"

else 

  elif  grep 'word1\|word2\|word3' startup.log
   then  
#if above word1 exists in file it should print below msg
  echo "hello"
  else 

#if word2 is present in file it shhould print below msg
    
         echo " world"

#   and one more contion i want to add like below

#if word3 is exists in the file it should below msg

   echo "postgresql"

構文を試してみましたが理解できませんでしたので、簡単な例1つを提供していただきありがとうございます。

ベストアンサー1

問題の説明に基づいてファイルに異なるパターンが見つかった場合は、別の操作を実行しようとしています。これにはさまざまな確認が必要です。

if grep -q word1 startup.log; then
echo "Message 1"
elif grep -q word2 startup.log; then
echo "Message 2"
elif grep -q word3 startup.log; then
echo "Message 3"
else
echo "Message 4"
fi

grep -qファイルが一致することを自動的に確認します。一致するパターンごとに表示する対応するメッセージを追加できます。

上記のロジックは単一のメッセージのみを表示します。ファイルに複数のパターンがある場合、if-elifチェーンの以前に指定されたパターンが優先されます。

各パターンを個別に確認するには、別々のifブロックを使用できます。

if grep -q word1 startup.log; then
echo "Message 1"
fi

if grep -q word2 startup.log; then
echo "Message 2"
fi

おすすめ記事