我想在一段时间后从shell脚本执行MySQL查询。我写了脚本,但输出不是预期的。它从数据库再次打印相同的值。有人可以帮忙。
SCRIPT - demo.sh
#!/bin/bash
echo "Shell Script to Query a Database!"
echo "--Querying from the Database starts--"
cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
for i in {1..5};
do
./mysql -u root -proot@123 << EOF
use catalyst_latest;
select id from ci_master limit 1;
EOF
echo "Wait for 2 seconds for the next ID."
sleep 2;
done
echo "--Query Stopped!--"
输出
$ ./demo.sh
Shell Script to Query a Database!
--Querying from the Database starts--
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
--Query Stopped!--
你能看到每次都有282人返回吗?所以我想在2秒后从数据库中获取下一个ID。请告诉我怎么做。 提前谢谢。
答案 0 :(得分:1)
您需要将返回的id
值记住到bash变量中,然后在查询的WHERE
子句中重用该变量,如下所示:
select id from ci_master where id > $id limit 1
要将命令的输出写入变量,请使用以下内容:
id=$(mysql <options> -Nsqe "<query>")
选项N
用于跳过列名(如id),选项s
用于更多静默输出,选项q
用于不缓存结果,选项e
用于命令执行。
最初,$id
变量应设置为某个值,如1或表中现有值的最小值。
答案 1 :(得分:0)
#!/bin/bash
echo "Shell Script to Query a Database!"
echo "--Querying from the Database starts--"
cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
for i in {1..10};
do
temp=`./mysql -u root -proot@123 << EOF
use catalyst_latest;
select id from ci_master limit $i;
EOF`
result=''
for j in $temp
do
result=$j
done
#date;
echo "$result"
echo "Wait for 1 seconds for the next ID."
sleep 1;
done
echo "--Query Stopped!--"