How to execute multiple sql files in postgreSQL linux?
-
14-07-2021 - |
Question
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.
Solution
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
OTHER TIPS
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