I have a Debian server and
I need a sh script which calls sql-script
in order to get some data from MySQL table
So I connect via ssh as root to my server and created all the files
Please note that I used full path to all the files in the script
in order to avoid misinterpretations.
/root/bin/mgbc.sh
#!/bin/sh
(echo "SET @cid=570; SET @cid2='service@';" ; cat /root/bin/mgbc.sql) |/full-path-to/mysql -uusername -pservetword > /root/bin/result_mgbc.txt
/root/bin/mgbc.sql
SELECT table1.id, table1.a_id, table2.email
FROM table1
INNER JOIN table2 ON table1.a_id=table2.id
AND table1.campaign_id = @cid
AND table2.email LIKE CONCAT('%', @cid2 ,'%')
;
let`s run it
*/root/bin/mgbc.sh*
and in the */root/bin/result_mgbc.txt*
I see
*table1.id
, table1.a_id
, table2.email
*
and lot of lines
Then I decided to put it as a crontab task
so I entered
crontab -e
and added a line
35 10 1 * * /root/bin/mgbc.sh
I see from a crontab log file that the script is started,
but in the */root/bin/result_mgbc.txt*
I see the field list only
table1.id, table1.a_id, table2.email
and no data at all.
Looks like @cid and @cid2 parameters are lost somewhere when the crontab runs the script.
Can anyone tell me what is going on and how to solve that?
Thank you in advance.
答案 0 :(得分:0)
将您的SET语句添加到mgbc.sql并像这样运行
/full-path-to/mysql -uusername -pservetword < /root/bin/mgbc.sql > /root/bin/result_mgbc.txt
或
/full-path-to/mysql -uusername -pservetword -e "SET @cid=570; SET @cid2='service@';" -e "$(cat /root/bin/mgbc.sql)" > /root/bin/result_mgbc.txt
或者您可以根据输入参数动态构建sql文件。
不确定这是否有用
/full-path-to/mysql -uusername -pservetword -e "SET @cid=570; SET @cid2='service@';" < /root/bin/mgbc.sql > /root/bin/result_mgbc.txt
答案 1 :(得分:0)
我终于找到了解决方案。 瓶颈是“%”
为了使一切正常,我需要这样做:
<强> /root/bin/mgbc.sh 强>
#!/bin/sh
(/bin/echo "SET @cid=570; SET @cid2='something@';" ; cat /root/bin/mgbc.sql) | /usr/bin/mysql -uusername -pservetword > /root/bin/result_mgbc.txt
SQL脚本
SET @percent := '%' ;
SELECT table1.id, table1.a_id, table2.email
FROM table1
INNER JOIN table2 ON table1.a_id=table2.id
AND table1.campaign_id = @cid
AND table2.email LIKE CONCAT(@percent, @cid2 , @percent)
;
SET @percent:='%'修复了isue,
因为 crontab 无法使用百分号。
感谢大家的帮助!