2014-11-21 33 views
0

我想超時在我的shell腳本中進行的過程中,例如,如果我想scp一個文件,如果該文件沒有在超時內通過錯誤轉移,如果成功回聲一個成功的消息,如何把超時?在shellcript中超時

回答

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)。比你必須編寫,調試和維護的自制解決方案要好得多。

+0

該死的,我知道我有一個更優雅的解決方案:D我想我在這裏學到了一個寶貴的教訓,儘管在shell腳本中進行一點練習絕不是壞事! – ShellFish 2014-11-21 12:29:08

+0

作爲一個練習,絕對不是。作爲發展時期,我不認爲這是事實。它通常會導致需要花費時間和精力維護的片狀代碼。 – 2014-11-22 05:06:30

+0

完全同意,因此我的投票支持你的答案。我不能相信我不知道這個內置命令順便說一句。 – ShellFish 2014-11-22 17:12:56