2014-01-19 78 views
1

我試圖做一個腳本,將參數上運行一個程序。 程序執行1分鐘後程序將退出。Bash腳本啓動程序,並在給定的時間退出

我的代碼如下所示:

pid=$(pidof $1) 
true=1 
$1 
while [ $true = 1 ] 
do 
time=$(ps -p $pid -o etime=) 
if $time > 01:00 
then 
    true=0 
    kill -9 $pid 
    echo "The process $pid has finish since the execution time has ended" 
fi 
done 

任何想法?程序午餐但不退出。

+0

真的沒有在bash中執行$ true檢查(':'爲true)的原因。只要做'while:';做',並在if塊結束時打破或退出。 – BroSlow

+2

使用一個簡單的'kill'而不是'kill -9',讓這個過程有機會在退出之前自行清理。 – chepner

回答

3

其實你的問題是這一行:

if $time > 01:00 

由於$time不能對01:00

您需要的時候先轉換成秒,這樣的比擬:

time=$(ps -p $pid -o etime= | awk -F ':' '{print $1*60 + $2}') 
if [[ $time -gt 60 ]]; then 
    # your if block code here 
fi 
+0

當你使用''''或'test'而不是'[[':'http://stackoverflow.com/questions/19597962/bash-illegal-number/19598570#19598570 –