Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple sql files in postgreSQL linux?

I have many .sql files in a folder (/home/myHSH/scripts) in linux debian. I want to know the command to execute or run all sql files inside the folder into postgreSQL v9.1 database.

PostgreSQL informations:

Database name=coolDB
User name=coolUser

Nice to have: if you know how to execute multiple sql files through GUI tools too like pgAdmin3.

like image 682
null Avatar asked Oct 25 '12 05:10

null


2 Answers

From your command line, assuming you're using either Bash or ZSH (in short, anything but csh/tcsh):

for f in *.sql;
do
    psql coolDB coolUser -f "$f"
done
like image 191
michel-slm Avatar answered Oct 14 '22 04:10

michel-slm


The find command combined with -exec or xargs can make this really easy.

If you want to execute psql once per file, you can use the exec command like this

find . -iname "*.sql" -exec psql -U username -d databasename -q -f {} \;

-exec will execute the command once per result.

The psql command allows you to specify multiple files by calling each file with a new -f argument. e.g. you could build a command such as

psql -U username -d databasename -q -f file1 -f file2

This can be accomplished by piping the result of the find to an xargs command once to format the files with the -f argument and then again to execute the command itself.

find . -iname "*.sql" | xargs printf -- ' -f %s' | xargs -t psql -U username -d databasename -q
like image 33
Russell Avatar answered Oct 14 '22 04:10

Russell