Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

linux - How can I execute an MySQL command through a shell script using if -else for condition based?

i am using this code for getting my desired output for automation purpose but always face error relate to if condition........

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

please help me to resolve this query.or correct this code i am new in shell script .

Thanks in advance!!!!!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Mysql won't understand if ..else shell syntax and so you will need to execute mysql within each if, else block with -e for execution e.g:

...
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
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...