Postgresql - query from bash script as database user 'postgres'
To execute a PostgreSQL query as the 'postgres' user, utilize the below command:
In the above command, make sure to replace dbname
with your database's name, table
with the table you want to execute the query on, and "SELECT * FROM table;"
with the SQL query you want to run. This command's magic is the seamless blend of sudo
for user switching, psql
for PostgreSQL command-line interface, and -c
to process a single-command query.
When handling sensitive data, try not to include credentials directly in your scripts. You might consider using environment variables or configuration files with proper permissions.
To streamline your output, use -t
for a clean tuples-only output and -X
to prevent psql
from reading the .psqlrc
file.
Ensure that the sudo
user running the script has the necessary permissions to impersonate 'postgres'.
Step-by-step guide
Running dynamic queries
To run dynamic SQL queries:
Capturing query results
To capture the result of a psql
query and use it further in your bash script:
Error handling
For better error management, apply the set -e
and set -u
options:
The script will immediately terminate when an error occurs (set -e
) and treat unset variables as an error (set -u
), saving you from nasty surprises.
Running complex queries
Ensuring secure access
- Avoid exposing sensitive details in logs or scripts. 😎
- Use password-less authentication methods for automated scripts.
Multi-line and complex queries
For multi-line or complex SQL queries, you can structure scripts for readability use 'EOF':
Maintaining transaction integrity
To ensure transaction integrity:
Was this article helpful?