4

Sort of like this question: Run all SQL files in a directory

I have files like: V1__some_migration.sql, V2__some_other_one.sql, etc

I was wondering how I could loop through and import these in some bash script based on the file name (bonus points if you know a way that works both on UNIX [OS X] and Linux [Ubuntu])

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201

1 Answers1

4

Loop through:

YOUR_DIR="/path/to/your/directory"
for file in $YOUR_DIR/*; do
    psql <insert your options here> "${file}"
done
hedgar2017
  • 1,425
  • 3
  • 21
  • 40
  • Maybe import is a bad word for it? We have a very small, not mission critical, backend service that needs migrations. The migrations are fairly simple but wanted an easy way loop through and import the migrations in a post deploy type hook. The SQL files themselves are written always as "if not exists" so they should be safe to run many times over. – Oscar Godson Jul 06 '17 at 19:30
  • About to try it! Thank you for such a fast response! – Oscar Godson Jul 06 '17 at 19:36
  • Using variable `PATH` is not very good idea. Also it will fail if file names contains spaces. – Abelisto Jul 06 '17 at 19:52
  • Oh, really, I didn't noticed :) No one should use spaces in Unix filenames. If fact, simple shell expansion has files already sorted. So ls | sort may be just *. It works with spaces. – hedgar2017 Jul 06 '17 at 19:55