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;"
3
  • stackoverflow.com/questions/6508267/… might be helpful Commented Nov 15, 2022 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. Commented Nov 15, 2022 at 16:21
  • I've already tried the solutions from stackoverflow.com/questions/6508267/…. That doesn't solve my problem. Commented Nov 16, 2022 at 7:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.