Home > Enterprise >  How to combine exec commands in shell script
How to combine exec commands in shell script

Time:11-03

I am running postgreSQL on docker. In order to access the container I run

winpty docker exec -it postgres_db bash

Now that I am inside the docker container, I run this to access as user 'postgres' in postgres server

psql -U postgres

Then what I want to do is create a database

create database test;

I can I do this sequentially in a script? I want something like this:

#!/bin/bash
winpty docker run -p 8005:5432 --name postgres_db -e POSTGRES_PASSWORD=password -d postgres
sleep 5
winpty docker exec -it postgres_db bash -c "psql -U postgres" [-c "create database test;"]

create database cannot be executed if im not inside "psql -U postgres". Obviously the last line -c "create database test;" is wrong, just to make you understand what I want to do.

CodePudding user response:

winpty docker exec -it postgres_db bash -c "psql -U postgres -c 'CREATE DATABASE test;'"

Both bash -c and psql -c take one shell word as input. A single or double quoted string is one word. You need to nest the quotes, just like the -c commands are nested.

Alternative:

winpty docker exec -it postgres_db bash -c "psql -U postgres -c \"CREATE DATABASE test;\""
  • Related