我找不到如何正确构造while循环以将给定Linux应用程序的所有崩溃记录到文本文件的方法。我想得到一个提示,以便我可以输入应用程序名称,然后输入一个循环以查看应用程序的pid。如果pid为null,我想将时间戳记记录在文本文件中并继续循环。如果在第二次迭代中仍为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

现在,脚本将回显:
What is the name of the application you want to monitor?runningStill monitoring...FAILURE: Crash occurred at: Wed May 22 01:44:53 EDT 2019 - Crashes will be logged in the monitoring tool directory under results.txtStill monitoring...FAILURE: Crash occurred at: Wed May 22 01:44:58 EDT 2019 - Crashes will be logged in the monitoring tool directory under 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

09-11 19:13