當我通過 cron 運行以下 bash 腳本時,最后一行在前一行完成之前運行。為什么?我怎樣才能執行我想要的命令?我確信這cron是罪魁禍首,但為了爭論,這里有一個虛擬的bash 腳本 (顯然,這只是一個例子。在現實世界中,我正在 python 程序中做一些工作,然后嘗試完成后將其工作產品復制到另一個地方。):#!/usr/bin/env bashcd /tmp/kier/scriptscript output -c "./sleeper.py; echo '...and we are done'"echo "This is the next line after invoking script..."...為了完整起見,這里是python 腳本,sleeper.py:#!/usr/bin/env python3import timeprint("python program starting")time.sleep(5)print("python program done")當我從命令行運行 bash 腳本時,一切都很好。具體來說,“This is the next line...”文本在 5 秒睡眠后的最后打印。但是當我從 cron 運行它時,輸出順序錯誤(這是 cron 運行作業后發給我的電子郵件):Script started, file is outputScript done, file is outputThis is the next line after invoking script...python program startingpython program done...and we are doneScript started, file is output所以你可以看到“這是下一行......”在 python 腳本真正啟動之前打印出來。就好像它在后臺運行 python 腳本一樣。我很難過。為什么會發生這種情況,如何讓echo命令等到scriptpython 程序運行完畢?(最后,是的,我可以在發送到的命令中包含我的額外命令script,我實際上正在考慮這一點。但是來吧!這太瘋狂了?。?
1 回答

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
我應該跟進并分享我想出的解決方案。最后,我從來沒有很好地回答為什么它在我的(RedHat)環境中以這種方式表現,所以我決定采用一種解決方法。我...
在調用“腳本”之前創建了一個哨兵文件,
在腳本的命令文本中包含一個額外的命令,用于刪除哨兵文件,然后
在繼續之前等待哨兵文件消失。
像這樣:
sentinel=`mktemp`
script output -c "./sleeper.py; rm $sentinel"
while [ -f $sentinel ]
do
sleep 3
done
是的,這是一個 hack,但我需要繼續前進。
添加回答
舉報
0/150
提交
取消