linux - 用于将所有应用程序崩溃事件写入文本文件的 Bash 脚本

标签 linux bash logging crash

我找不到如何正确构造我的 while 循环以将给定 Linux 应用程序的所有崩溃记录到文本文件中。我想得到一个提示,这样我就可以输入应用程序名称,然后循环查看应用程序的 pid。如果 pid 为空,我想在文本文件中记录时间戳并继续循环。如果在第二次迭代时仍然为 null,则不记录任何内容,继续监视直到出现其他崩溃和其他日志...等等,直到脚本通过 CTRL+C 停止。

我试过这个脚本的多种变体,但都没有成功。我想我需要有关如何考虑“循环结构”以实现任何目标的提示...

read -p "What is the name of the application you want to monitor?" appname

pidofapp=`ps -elf | grep "$appname" | grep -v grep | awk '{print $4}'`
pidofappcheck=`ps -elf | grep "$appname" | grep -v grep | awk '{print $4}'`

while :
do
if [[ ! -z "$pidofappcheck" ]] ; then
        pidwasnull=true
pidofappcheck=`ps -elf | grep "$appname" | grep -v grep | awk '{print $4}'`
if [[ "$pidofapp" == "$pidofappcheck" ]] ; then
        printf "Still monitoring...\n"
        sleep 5
elif [[ "$pidwasnull" == true ]] ; then
        continue
fi
        echo "FAILURE: Crash occurred at: "$(date)" - Crashes will be logged in the monitoring tool directory under results.txt"
        date >> ./results.txt
fi
done

就像现在一样,脚本将回显:

您要监控的应用程序名称是什么?running 还在监控中…… 失败:崩溃发生在:美国东部时间 2019 年 5 月 22 日星期三 01:44:53 - 崩溃将记录在 results.txt 下的监控工具目录中 还在监控中…… 失败:崩溃发生在:美国东部时间 2019 年 5 月 22 日星期三 01:44:58 - 崩溃将记录在 results.txt 下的监控工具目录中

在此先感谢您的帮助。

最佳答案

尝试这样的事情

#!/bin/bash
getpidofapp() {
   # pid=$(ps -elf | grep "$1" | grep -v grep | awk '{print $4}' | head -1)
   pid=$(pgrep "$1" | head -1)
   test -n "${pid}" || { echo "Is ${appname} running?"; exit 1; } 
}

read -rp "What is the name of the application you want to monitor?" appname
app_pid=$(getpidofapp "${appname}")

while : ; do
   lastpid=$(getpidofapp "${appname}")
   if [[ "${app_pid}" == "${lastpid}" ]] ; then
        printf "Still monitoring...\n"
   else
      crashtxt="Crashes will be logged in the monitoring tool directory under results.txt"
      echo "FAILURE: Crash occurred at: $(date) ${crashtxt}"
      date >> ./results.txt
   fi
   sleep 5
done

关于linux - 用于将所有应用程序崩溃事件写入文本文件的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250323/

相关文章:

python - 为什么我的代码无法检测到操纵杆上的按钮按下

linux - 如何使用 Cygwin 在 Expect 脚本中配置超时?

python - 当我在 Bash 中有一系列命令时,如何重定向标准输入/标准输出?

r - 如何制作 R session 的日志文件,该文件结合了来自 R 控制台的命令、结果和警告/消息/错误

linux - 如何解决这个不明确的重定向错误

python - 在 Linux 中安装 Django 时出现无效语法错误

java - 忽略子线程生成的日志

Python 日志记录方面的最佳实践

linux - Linux 中的命令替换 - 在 bashrc 中设置变量(用户名和密码)

linux - grep + 如何忽略许多标记行的情况