我想超時在我的shell腳本中進行的過程中,例如,如果我想scp一個文件,如果該文件沒有在超時內通過錯誤轉移,如果成功回聲一個成功的消息,如何把超時?在shellcript中超時
0
A
回答
0
使用此例如:
command & # start a new process in background
pid=$(pidof command | cut -f1 -d' ') # save pid of started process
sleep(timeout_value) # set timeout value to match your desired time to process
pids=$(pidof command) # get all pids of running processes of this command
if [[ $(grep "$pid" "$pids") ]]; then # if started process still running
echo "error"
else
echo "success"
fi
更改Word命令,以符合您實際的命令。我不確定這是否可以用管道工作,我會在一分鐘內測試一下,然後回覆給你。
對於管道命令,你可以做以下(假設您正在執行使用bash):
(command | other_command | ...) &
pid=$(pidof bash | cut -f1 -d' ') # save pid of started process
sleep(timeout_value) # set timeout value to match your desired time to process
pids=$(pidof bash) # get all pids of running bash processes
if [[ $(grep "$pid" "$pids") ]]; then # if started process still running
echo "error"
else
echo "success"
fi
問題
注意,有更好的答案在那裏,因爲這劇本總是會等待整個超時。這可能不是你想要的。
可能的解決方法
一個可能的解決方案就是睡覺多次,這樣的事情:
for i in $(seq 1..100); do
sleep(timeout/100) # sample the timeout interval
pids=$(pidof bash)
if [[ $(grep -v "$pid" "$pids") ]]; then # if process no longer running
echo "succes" && exit 0 # process completed, success!
elif [[ $i -eq 100 ]]; then
echo "error" # at the end of our timeout
fi
done
注:更改值100,如果你超時很長,嘗試優化它,每次迭代超時不會太長。
1
使用timeout(1)
。比你必須編寫,調試和維護的自制解決方案要好得多。
相關問題
- 1. 防止shellcript中的命令在另一個shellcript內執行
- 2. Ubuntu shellcript
- 3. 在shellcript中創建兩個圖像
- 4. 如何在shellcript中執行psql時添加shell命令
- 5. 轉換shellcript代碼到c
- 6. 獲取shellcript輸入密碼
- 7. 如何在多行字符串shellcript中傳遞變量的值
- 8. 在MYSQL中超時
- 9. 在SOA中超時
- 10. 在RxJava中超時
- 11. Hudson vs使用shellcript有什麼優勢?
- 12. 從shell或shellcript寫入shell腳本?
- 13. 在popen中超時工作,但在超時內popen不?
- 14. 在Calabash測試中超時
- 15. 在angularjs中修改超時
- 16. 在TCP中設置超時
- 17. 在CUDA中超時?/fermi/gtx465
- 18. 在c#測試中超時
- 19. 在Webview中處理超時
- 20. ScheduledExecutorService在超時後中斷
- 21. 在QML中超時XMLHttpRequest
- 22. 在SQL過程中超時
- 23. 在Ext Direct中超時
- 24. 在android中的GPS超時
- 25. LocationProvider在BlackBerry 6.0中超時?
- 26. 防止在PHP中超時
- 27. 在c中實現超時#
- 28. 在QT中實現超時
- 29. 在subprocess.check_output中添加超時
- 30. 在wsclient中指定超時
該死的,我知道我有一個更優雅的解決方案:D我想我在這裏學到了一個寶貴的教訓,儘管在shell腳本中進行一點練習絕不是壞事! – ShellFish 2014-11-21 12:29:08
作爲一個練習,絕對不是。作爲發展時期,我不認爲這是事實。它通常會導致需要花費時間和精力維護的片狀代碼。 – 2014-11-22 05:06:30
完全同意,因此我的投票支持你的答案。我不能相信我不知道這個內置命令順便說一句。 – ShellFish 2014-11-22 17:12:56