スクリプトの実行中にスクリプトの出力が同じログファイルに書き込まれると、スクリプトからログファイルを読み取ることができますか?

スクリプトの実行中にスクリプトの出力が同じログファイルに書き込まれると、スクリプトからログファイルを読み取ることができますか?

some_log_file.log ファイルに出力を書き込むシェルスクリプトがあります。

{

some logic..

if grep -iq "No such file or directory" some_log_file.log ; then

some logic to send email.. attaching the same some_log_file.log

fi

} >> some_log_file.log 2>&1

上記のコードを見ると、スクリプトが実行されているときに記録されているのと同じログファイルを確認していることがわかります。これはうまくいきます。しかし、これは許可されており、標準ですか?

ベストアンサー1

はい、許可されています。いいえ、これは非常に一般的または標準ではないと思います。しかし、今動作するので、そのままにすることができます。

しかし、Pankiの観点からは、ログをgrepするよりも、「該当するファイルやディレクトリなし」を報告できるコマンドの終了状態(リターン状態とも呼ばれる)を確認する方が良く、より効率的です。

$?変数には、常に実行された最後のコマンドの終了ステータスが含まれます。通常、0 はコマンドが正常に実行されたことを示します。正の値(1、2、99など)の場合、これはエラーの種類を示します。たとえば、

>> ls /usr/bin/sed
-rwxr-xr-x  1 root  wheel  202960 May  9 15:30 /usr/bin/sed
>> echo $?
0

>> ls -l nonexistent_file
ls: nonexistent_file: No such file or directory
>> echo $?
1

コマンドで「該当するファイルやディレクトリはありません」と報告できます。 ftpとは何ですか?単純化のために「ls」と仮定しましょう。スクリプトは次のとおりです。

ls $my_file  # Or whatever your command is.
if [ $? = 1 ]; then
    # Send mail ...
fi

# Alternatives:

ls $my_file  # Or whatever your command is.
if [ $? != 0 ]; then
    # Send mail ...
fi

ls $my_file  # Or whatever your command is.
status=$?
case $status in
    0) : ;;  # Success, do nothing.
    1) Send mail ... ;;
    *) echo "Error: \"ls $my_file\"." returned status $status."
       exit 99;;
esac

コマンドがftpの場合、コマンドには以下で説明するより複雑なステータスコードがあります。

https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes

そしてここ:

https://docs.microsoft.com/en-us/troubleshoot/developer/webapps/iis/ftp-service-svchost-inetinfo/ftp-status-codes-iis-7-and-later-versions

-f(follow)オプションを指定してtailコマンドを使用して調べることもできます。たとえば、バックグラウンドで次のコマンドを実行できます。

tail -f some_log_file.log | grep -iq "No such file or directory"

詳細については、tailのマニュアルページを参照してください。

しかし、終了状態($?)を使用することが最善の選択になると思います。

おすすめ記事