2015-08-17 171 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