程序未如預期執行

程序未如預期執行

我有以下 bash shell 腳本,90% 的時間都可以完成預期的任務,但有時卻不能。問題在於日期和時間的位置。如圖所示,我已告訴程式date在 的末尾附加screenlog.0。大多數時候,這種情況都會正常發生。但是,有時日期和時間會附加到開始screenlog.0。這確實很麻煩,因為格式screenlog.0需要遵守一定的準則。任何幫助,將不勝感激。

#!/bin/bash
...
...

if grep -q "dicounter_${string1}_from_${string2}" MasterFile.txt || [ -e "dicounter_${string1}_from_${string2}" ];
then
   echo "dicounter_${string1}_from_${string2} already exists in the MasterFile or the current directory. Would you like to proceed?"
   read string3
   if [[ "${string3^}" == 'Y' ]]; then
      echo "How many times has this dicounter been retested? (e.g. 1 for first time, 2 for the second, ...)"
      read string4
      screen -S trans -L /dev/ttyACM0
      screen -S trans -X stuff 's'$(echo -ne '\015')
      sleep 8s
      screen -S trans -X quit
      date +%F~%H:%M:%S >> screenlog.0
      mv screenlog.0 dicounter_${string1}_from_${string2}~${string4}

   else
      exit 0
   fi
else
  #opening screen & begin analysis
  screen -S trans -L /dev/ttyACM0
  screen -S trans -X stuff 's'$(echo -ne '\015')
  sleep 8s
  screen -S trans -X quit
  date +%F~%H:%M:%S >> screenlog.0
  mv screenlog.0 dicounter_${string1}_from_${string2}

fi

本質上,該程式是查看是否dicounter_..._from_...已經存在,如果不存在,或者使用者是否想要另一次測試運行,請繼續並連接到發射器並獲取資料。最後,screenlog.0建立一個文件,我想在文件末尾附加日期和時間。然後重命名它。

答案1

似乎螢幕“退出”命令在刷新日誌之前返回。在最終螢幕命令和日期戳記之間添加延遲應該允許螢幕有時間完成寫入日誌。另一個選擇是使用“忙”循環來等待日誌寫入:

...
screen -S trans -X quit
while [ ! -s screenlog.0 ]
do
  sleep 1
done
date +%F~%H:%M:%S >> screenlog.0
...

相關內容