运行bash脚本而不是单个文件执行两个

时间:2019-02-27 22:26:41

标签: bash

#!/bin/bash

results=($(mysql --user xxx -pxxxxx asterisk -Bse "SELECT id,did From global_did WHERE status='no' LIMIT 1 ;"))

cnt=${#results[@]}
for (( i=0 ; i<cnt ; i++ ))
do

cat << EOFTEST1 > /etc/asterisk/script/$((1 + RANDOM % 1000))-255621067201
Channel: Local/255621067201@dialer
MaxRetries: 0
WaitTime: 30
Context: informer
Extension: 255621067201
Callerid: ${results[1]}
Account: Tanzania
Priority: 1

EOFTEST1

UPDATED=${results[0]}
mysql --user=xxxx --password=xxxx asterisk -Bse "UPDATE global_did SET status='yes' WHERE id='${UPDATED}';"

我将它设置为具有随机数 $((1 + RANDOM%1000)),执行时它会生成两个文件而不是一个,我在做什么错了?

1 个答案:

答案 0 :(得分:1)

for循环对查询返回的每一列执行一次。由于查询返回两列,因此$cnt2,您将执行两次代码,并获得两个文件。摆脱循环。

如果要允许查询返回不止一行,并为每一行执行循环,则应将$i加2,而不是1,并在数组索引中使用$i而不是硬编码12

for (( i=0 ; i<cnt ; i+=2 ))
do

    cat << EOFTEST1 > /etc/asterisk/script/$((1 + RANDOM % 1000))-255621067201
Channel: Local/255621067201@dialer
MaxRetries: 0
WaitTime: 30
Context: informer
Extension: 255621067201
Callerid: ${results[$i+1]}
Account: Tanzania
Priority: 1

EOFTEST1

    UPDATED=${results[$i]}
    mysql --user=xxxx --password=xxxx asterisk -Bse "UPDATE global_did SET status='yes' WHERE id='${UPDATED}';"
done