HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

connect to psql and run SQL command from command line

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
connectlinesqlpsqlandcommandfromrun

Problem

I'm trying to write a quick line in bash that will use psql to connect to a database and delete all entries in two tables:

\connect some_db
DELETE from some_table
DELETE from another_table


I'd like to do this in one line of bash scripting like so:

psql -U  -c "\c some_db; DELETE from some_table; DELETE from another_table"


but it seems like I can't do that because the \c command creates a new context that the subsequent commands don't apply towards.

What's the right way to do this in a line or two from the CLI?

Solution

You don't need the \c in the command specified with -c, you can specify the database as a parameter to psql:

psql -U  -d some_db -c "DELETE from some_table; DELETE from another_table"

Code Snippets

psql -U <username> -d some_db -c "DELETE from some_table; DELETE from another_table"

Context

StackExchange Database Administrators Q#123153, answer score: 6

Revisions (0)

No revisions yet.