![ディレクトリから最新の更新ファイルを選択し、電子メールで送信します。](https://linux33.com/image/68458/%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%81%8B%E3%82%89%E6%9C%80%E6%96%B0%E3%81%AE%E6%9B%B4%E6%96%B0%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%92%E9%81%B8%E6%8A%9E%E3%81%97%E3%80%81%E9%9B%BB%E5%AD%90%E3%83%A1%E3%83%BC%E3%83%AB%E3%81%A7%E9%80%81%E4%BF%A1%E3%81%97%E3%81%BE%E3%81%99%E3%80%82.png)
特定のディレクトリで最新のエラー(タイムスタンプ).logファイルを選択して、電子メールで添付ファイルに送信したいと思います。私が試していることは次のとおりです。
ファイル名: abc.sh
echo 'An error occured' | mutt -s "Logs" -a '/xx/xx/logs/xx/*.log(.om[1])' -e 'my_hdr From:[email protected]' -- [email protected]
答え1
シンプルなソリューション
私はあなたのログファイル名がglobと一致し、/xx/xx/logs/xx/*.log
あなたが次のアドレスにメールを送信したいと仮定します。[email protected]
newest=$(ls -rt /xx/xx/logs/xx/*.log | tail -n 1)
echo 'An error occured' | mutt [email protected] -s "Logs" -a "$newest"
この方法は、ファイル名が良い場合に機能します。ただし、通常、解析された出力ls
は信頼できません。
より安定したソリューション
これは使用を避け、ls
すべてのファイル名に対して安全です。
inode=$(find /xx/xx/logs/xx/ -maxdepth 1 -type f -iname '*.log' -printf '%T@ %i\n' | sort -rn | awk '{print $2;exit;}')
newest=$(find /xx/xx/logs/xx/ -maxdepth 1 -inum "$inode")
echo 'An error occured' | mutt [email protected] -s "Logs" -a "$newest"
どのファイルが選択されたかをテストする
電子メールで送信せずにどのファイルが最新であるかを確認するには、次の手順を実行します。
inode=$(find /xx/xx/logs/xx/ -maxdepth 1 -type f -iname '*.log' -printf '%T@ %i\n' | sort -rn | awk '{print $2;exit;}')
newest=$(find /xx/xx/logs/xx/ -maxdepth 1 -inum "$inode")
echo "newest file is $newest"