Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Last active April 19, 2022 13:12
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dantheman213/a281a0f7364218bfd1013565aac28830 to your computer and use it in GitHub Desktop.
Save dantheman213/a281a0f7364218bfd1013565aac28830 to your computer and use it in GitHub Desktop.
Batch import all *.sql files in a folder recursively into your Postgres or PostgreSQL database
#!/bin/sh
# AUTHOR
# DANIEL E. GILLESPIE (2016)
# https://github.com/dantheman213
# DESCRIPTION
# Import all *.sql files in a folder recuresively into your PostgreSQL database
# Batch export all table schemas and stored functions with this script located here:
# https://gist.github.com/dantheman213/aff70ee42a11f2d1fa46983878cd62e1
# INSTALLATION
# 1. Install script at /usr/bin or /usr/sbin (if you
# want to make this root/admin privs only)
# 2. chmod +x /usr/bin/import_db_structure.sh
# 3. Make sure your Postgres database will accept a local
# connection with password authentication
# 4. Execute the script.. pass in import folder path as an argument
### CHANGE THESE TO YOUR SERVER/APP INFO ###
POSTGRES_USER="postgres"
POSTGRES_PASSWORD="postgres"
DATABASE_NAME="myapp_db"
### END CONFIGURATION ###
if [[ $# -eq 0 ]] ; then
echo 'Please enter the folder where you want to import all *.sql files under it.'
exit 0
fi
echo "Cleaning up cache..."
/etc/init.d/postgresql stop
echo 1 > /proc/sys/vm/drop_caches
/etc/init.d/postgresql start
echo "Importing..."
export PGPASSWORD=$POSTGRES_PASSWORD
for file in `find $1 | grep -i '.sql'`
do
echo "importing $file"
psql -U $POSTGRES_USER $DATABASE_NAME < $file
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment