1

How to create the schema 'testschema' in the database 'testdb' using bash script?

The database is running in a docker container. I've created a bash script that has following lines: DB_NAME='testdb' schm='testschema'

PGPASSWORD=$PGPASS psql -X -h localhost -p $DB_PORT -U postgres -c "CREATE DATABASE $DB_NAME;"
PGPASSWORD=$PGPASS psql -X -h localhost -p $DB_PORT -U postgres -c "CREATE SCHEMA $schm;"

After executing this it will create a schema but in postgres db. That is not what I want.

If I add a db name then it produces an error:

PGPASSWORD=$PGPASS psql -X -h localhost -p $DB_PORT -U postgres -c "CREATE SCHEMA $DB_NAME.$schm;"
Alex Belke
  • 13
  • 3
  • https://stackoverflow.com/questions/6508267/postgresql-create-schema-in-specific-database might be helpful – j_b Nov 15 '22 at 16:18
  • Add a `-d $DB_NAME` switch to your `psql` calls, after creating this database. The thread linked above does mention this but in the last, least upvoted answer. – Zegarek Nov 15 '22 at 16:21
  • I've already tried the solutions from https://stackoverflow.com/questions/6508267/postgresql-create-schema-in-specific-database. That doesn't solve my problem. – Alex Belke Nov 16 '22 at 07:10

1 Answers1

0

Add a -d $DB_NAME switch to your psql calls, after creating this database.

PGPASSWORD=$PGPASS psql -X -h localhost -p $DB_PORT -U postgres -c "CREATE DATABASE $DB_NAME;"
PGPASSWORD=$PGPASS psql -X -h localhost -p $DB_PORT -U postgres -d $DB_NAME -c "CREATE SCHEMA $schm;"

Without specifying the database psql defaults to postgres. From man psql:

-d dbname

--dbname=dbname

Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line. The dbname can be a connection string. If so, connection string parameters will override any conflicting command line options.

Zegarek
  • 6,424
  • 1
  • 13
  • 24