[英]Running mysql query from bash; where query is stored in a separate file w/ variables set in bash
I have a bash script that is responsible for querying a database and piping the results to a file:我有一个 bash 脚本,负责查询数据库并将结果传送到文件:
date=`date +"%Y/%m/%d"`
/usr/bin/mysql -u $db_user -p$db_pass -h $db_name $db_schema << MYSQLEOF > $output_file
select *
from table
where date = $date
MYSQLEOF
Now expanding this project into other areas, for the sake of re-usability/orthogonality I wanted to house the query in it's own file and call with something like:现在将此项目扩展到其他领域,为了可重用性/正交性,我想将查询放在它自己的文件中,并使用以下内容进行调用:
cmd=`echo $sql_file`
/usr/bin/mysql -u $db_user -p$db_pass -h $db_name $db_schema -e "$cmd" > $output_file
sql file: sql文件:
select *
from table
where date = $date
I am having trouble finding out how I can (in bash) do this, while still being able to have and adjust variables ($date) inside the sql file.我在找出如何(在 bash 中)执行此操作时遇到了麻烦,同时仍然能够在 sql 文件中拥有和调整变量($date)。 Echoing the .sql file into a bash variable, I haven't been able to get "$date" to not be taken as a literal string.
将 .sql 文件回显到 bash 变量中,我无法让“$date”不被视为文字字符串。
Is there a solution in bash, or should I look into something like perl to handle this? bash 中是否有解决方案,或者我应该研究 perl 之类的东西来处理这个问题?
Use the mySQL CLI's source
command.使用 mySQL CLI 的
source
命令。
queryfile=my_query.sql
/usr/bin/mysql -u $db_user -p$db_pass -h $db_name $db_schema -e "source $queryfile" > $output_file
I found a solution using command-line Perl to search/replace on the fly.我找到了一个使用命令行 Perl 来动态搜索/替换的解决方案。
Bash script: bash脚本:
date=`date +"%Y/%m/%d"`
export date
cmd=`perl -lpe 's/DATE_VAR/$ENV{date}/g' "$sql_file"`
/usr/bin/mysql -u $db_user -p$db_pass -h $db_name $db_schema -e "$cmd" > $output_file
and in sql_file:并在 sql_file 中:
select *
from table
where date = 'DATE_VAR'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.