我找不到如何正确构造我的 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/