简体   繁体   English

如何将bash变量传递到sql文件

[英]How to pass a bash variable into an sql file

I have a bash script to call a select in postgres. 我有一个bash脚本来调用postgres中的select。 I would like to be able to pass a variable from the command line into the sql file. 我希望能够从命令行将变量传递到sql文件中。

sh myscript.sh 1234

#!/bin/bash
dbase_connect="psql -h server -U username dbase"
file="/tmp/$fname.csv"
sql="/home/user/sql_files/query.sql"

sudo bash -c "$dbase_connect -c -q -A -F , -f $sql -o $file"

The query can be as simple as: 查询可以很简单:

select name from table where id = $1;

But I don't know how to call the $1 into the sql file. 但是我不知道如何在SQL文件中调用$1 The actual query is much larger and I prefer to keep it out of the bash query itself because it is easier to maintain when called as a seperate .sql file. 实际的查询要大得多,我更喜欢将其排除在bash查询之外,因为当作为单独的.sql文件调用时,它更易于维护。

you can use sed to insert parameter : 您可以使用sed插入参数:

#!/bin/bash
dbase_connect="psql -h server -U username dbase"
file="/tmp/$fname.csv"
sql="/home/user/sql_files/query.sql"
tmp="home/user/sql_files/query.sql.tmp"
s="s/\$1/$1/g"
cat $sql | sed $s > $tmp

sudo bash -c "$dbase_connect -c -q -A -F , -f $tmp -o $file"
rm -f $tmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM