Navdeep Singh
Navdeep Singh

Reputation: 161

execute sql files from a folder in postgres

I have a set of sql files placed in a folder in postgres docker image. Whenever a new account is created, I want a new database to be created and all these scripts should get executed on that new created database.

New database will be created manually. I need to create sh file to ask for db name, host, port, password etc and then execute all sql files on new created database.

I tried and I can execute one single file

psql -h localhost -d sampledb -U superuser -f sample.sql

I need to execute all files in the folder. How I can achieve this.

Upvotes: 0

Views: 1349

Answers (1)

Sreejith
Sreejith

Reputation: 464

Here, you can make use of small bash script. Copy all your sql files to a folder, for example test. Then execute the below line of script.

for i in $(ls -l test/*.sql |awk '{print $NF}'); do 
    psql -h localhost -d sampledb -U superuser -f $i; 
done

Upvotes: 2

Related Questions