Question

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.

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.

Était-ce utile?

La solution

you can use sed to insert parameter :

#!/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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top