13

I'm trying to write PostgreSQL script(s) but having a problem with shebang line

#! /usr/bin/psql [ psql_args_here ] -f

select now();

This gives me error as if I just entered psql without any arguments in command line. How do I do it right?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Mark Gurevich
  • 228
  • 2
  • 9

2 Answers2

17

The problem is that psql don't skip the first line of the file.

You could try

#! /bin/sh
exec sh -c "tail -n +3 $0 | psql -f -"

select now();

or simply

#! /bin/sh
psql << E_O_SQL

select now();

E_O_SQL
mnencia
  • 3,298
  • 1
  • 23
  • 35
7

There is a even better solution. The first line should be:

--() { :; }; exec psql -f "$0"

It works as a regular shebang #!

http://rosettacode.org/wiki/Multiline_shebang#PostgreSQL

AngocA
  • 7,655
  • 6
  • 39
  • 55
  • The explanation of why it works is here: https://unix.stackexchange.com/a/488070/41086 @Kusalananda – AngocA Jul 27 '20 at 16:26