2

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works perfectly and gave me an idea to consolidate another script (less maintenance later).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.