我有一个bash脚本,可以通过电子邮件从远程数据库中删除一些记录。
for email in "$@"; do
heroku pg:psql << EOF
DELETE FROM table1 WHERE email='$email';
DELETE FROM table2 WHERE email='$email';
DELETE FROM table2 WHERE email='$email';
EOF
done
当我执行它时,它当然有效但我连接多次到Heroku:
./scripts/delete-account.sh email1@example.com email2@example.com
---> Connecting to DATABASE_URL
DELETE 0
DELETE 0
DELETE 0
---> Connecting to DATABASE_URL
DELETE 0
DELETE 0
DELETE 0
有没有办法首先构建这个SQL语句然后立即执行它?
我知道我可以采用命令式方法,创建变量,在循环中修改它然后将其传递给pg:psql
命令,但我不认为它是最好的和唯一的方法就是这样做。
答案 0 :(得分:0)
为什么不使用脚本构建所有 SQL语句,然后将其传递给psql命令?
$cat ./scripts/delete-account.sh
(for email in "$@"; do
echo "DELETE FROM table1 WHERE email='"$email"';"
echo "DELETE FROM table2 WHERE email='"$email"';"
echo "DELETE FROM table2 WHERE email='"$email"';"
done) | heroku pg:psql
然后将其命名为:
$./scripts/delete-account.sh email1@example.com email2@example.com
另外,注意引用,shell不会在单引号内插入
(尝试email=a@b.com;echo '$email'
,看看会发生什么)。