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

时间:2021-07-23 15:45:44

I have a bash script to call a select in postgres. I would like to be able to pass a variable from the command line into the sql file.

我有一个bash脚本来调用postgres中的select。我希望能够将命令行中的变量传递给sql文件。

sh myscript.sh 1234

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

但我不知道如何将$ 1调用到sql文件中。实际查询要大得多,我更喜欢将它保留在bash查询本身之外,因为当作为单独的.sql文件调用时,它更容易维护。

1 个解决方案

#1


3  

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

#1


3  

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