这是我的问题。我有一组 SQL 数据库查询,我使用 shell 脚本和相应的扩展名为 .sql 的批处理文件来触发这些查询。我的一些查询需要一些手动用户输入(根据请求),但我在脚本中没有成功实现。
到目前为止,我通过 shell 脚本将用户输入作为日期接收:
echo "Please specify the date in yyyy-mm-dd format: 'input;"
read input
mysql -u user -ppass < batch_file.sql
我想将变量 $input
传递到批处理文件。
正在执行的 SQL 查询的批处理文件如下所示:
select count(*) as count from subscriptions
where date_add(optin_date, interval 1 year) between "$input"
and date(curdate())
and active = 1
and stype = "domain";
其中"$input"
是从shell脚本传递下来的变量。
如有任何想法,我们将不胜感激,谢谢。
最佳答案
尝试在脚本中使用here-doc来执行此操作:
#!/bin/sh
echo "Please specify the date in yyyy-mm-dd format: 'input;"
read input
mysql -u user -ppass <<EOF
select count(*) as count from subscriptions
where date_add(optin_date, interval 1 year) between "$input"
and date(curdatE())
and active = 1
and stype = "domain";
EOF
如果您因任何原因无法使用第一个解决方案,请使用另一个解决方案:
echo "Please specify the date in yyyy-mm-dd format: 'input;"
read input
sed -i "s/\"\$input\"/$input/g" batch_file.sql
mysql -u user -ppass < batch_file.sql
如果您更喜欢第二种解决方案,最好在 SQL 文件中使用 %%PATTERN%%
而不是 $input
进行替换。
关于mysql - MYSQL 接受用户输入? Shell 脚本/批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753721/