首页 > 解决方案 > 如何使用 if -else 基于条件通过 shell 脚本执行 MySQL 命令?

问题描述

我正在使用此代码为自动化目的获取我想要的输出,但总是面临与 if 条件相关的错误......

mysql  --login-path=local << EOF >/home/test.sql

use testdb;

if ([$(date +%m) -eq 1] | [$(date +%m) -eq 3] | [$(date +%m) -eq 5] | [$(date +%m) -eq 7] | [$(date +%m) -eq 8] | [$(date +%m) -eq 10] | [$(date +%m) -eq 12])

then
  
select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d  "tomorrow -31 days")' and '$(date +%F)' and action='AUTH' ;

elseif [$(date +%m) -eq 2 ]

then
 
 select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d  "tomorrow -28 days")' and '$(date +%F)' and action='AUTH' ;

else

  select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d  "tomorrow -30 days")' and '$(date +%F)' and action='AUTH' ;

fi 

EOF

请帮我解决这个查询。或者更正这个代码,我是 shell 脚本的新手。

提前致谢!!!!!!!

标签: mysqllinuxshell

解决方案


Mysql 无法理解 if ..else shell 语法,因此您需要在每个 if 中执行 mysql,否则使用 -e 阻止执行,例如:

...
elseif [ "$(date +%m)" -eq 2 ]
then
 mysql --login-path=local -e "use testdb;select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d  "tomorrow -28 days")' and '$(date +%F)' and action='AUTH' ;" >> /home/test.sql
else
...

推荐阅读