2015-08-17 207 views
0

我想寫一個基本上會查詢給定條件的shell腳本。這是抓住。我想讓它重複查詢3分鐘。 (可能運行查詢,並休眠2秒)編寫一個shell腳本

1分鐘後,如果查詢返回null,任何時候for循環都會中斷。 (主要目的是檢測查詢始終返回結果爲3分鐘的時間)

如何結合在下面的代碼break語句檢查,1分鐘後? (不SPOOL覆蓋文件的內容,或者它追加?)

for ((i=90; i > 1 ; i--)) 
    do 
    sqlplus -s username/[email protected] <<EOF 
    SET PAGESIZE 50000 
    SET TERM OFF 
    SET HEAD OFF 
    SET LINESIZE 200 
    #SET TRIMSPOOL ON 
    SET FEEDBACK OFF 

    SPOOL /appl/odd/local/bin/notification_pending.txt 
    select awb,rcvr_phone,rcvr_email,latest_event,latest_event_dtm,status,contact,notify_method from shipment t,notification t2 where t.id=t2.shp_id 
    and t2.status like 'F%' 
    and t2.contact not in ('Recipient not in whitelist','Invalid Email Id','Mail Service Down','Invalid Mobile Number'); 

    SPOOL OFF 
    exit 
    /
    EOF 
    sleep 2 
done 
+0

爲什麼不在儲存的程序包或程序中調用這一切? – kevinsky

+0

看到http://stackoverflow.com/questions/27971833/in-bash-heredoc-inside-function-returns-syntax-error的一些想法。注意'dbname = $(...)'結構。祝你好運。 – shellter

+0

@kevinsky,我不使用存儲過程,因爲我相信在Shell腳本,它將不能夠閥芯結果到一個文件,以電子郵件通知。 – JCDrew90

回答

2

做最簡單的事情是捕捉sqlplus輸出,然後測試,如果結果字符串爲空。爲了便於閱讀,我打電話到sqlplus在一個函數。鑑於您使用的for聲明的形式,我還假設您正在使用bash

run_query() { 
sqlplus -s username/[email protected] <<EOF 
# [deleted] 
EOF 
} 

# SECONDS is incremented each second, so can be used as 
# a simple timer. 
SECONDS=0 

# For the first minute, just run the query 
while ((SECONDS <= 60)); do 
    output=$(run_query) 
    sleep 2 
done 

# After the first minute, continue running the query for the 
# next two minutes, but quit if the query produces no output. 
while ((SECONDS <= 180)); do 
    output=$(run_query) 
    if [[ -z $output ]]; then 
     break 
    fi 
    sleep 2 
done 

或者,你可以結合兩個迴路,並使用一個稍微複雜一點的條件內:

while ((SECONDS <= 180)); do 
    output=$(run_query) 
    # Don't break for any reason during the first 60 seconds 
    if ((SECONDS > 60)) && [[ -z $output ]]; then 
     break 
    fi 
    sleep 2 
done 

如果你不使用bash,你可以調用模擬定時器date

start=$(date +%s) 
while now=$(date +%s); SECONDS=$((now - start)); [ "$SECONDS" -le 180 ]; do 
    output=$(run_query) 
    if [ "$SECONDS" -gt 60 ] || [ -n "$output" ]; then 
     break 
    fi 
    sleep 2 
done 
+0

謝謝Chepner! if條件中的-z表示值是否爲零? – JCDrew90

+0

零長度,即如果'$ output ==「」'。 – chepner