Sub topic 6
Running Commands and Script Files from `psql`
This chapter assumes you know basic SQL, can use a terminal, and can connect to a PostgreSQL database. You also need access to a database such as mydb. The psql commands in this chapter run SQL without requiring you to stay in an interactive session.
Run one command with `-c`
Use -c to give psql one command to run. The client connects, executes the command, prints the result, and exits.
psql -d mydb -c '\dt public.*'
psql -d mydb -c 'SELECT count(*) FROM public.orders;'The first command uses a psql meta-command to list tables. The second sends SQL to PostgreSQL. Shell quoting keeps the command together as one argument.
You can provide connection options when the database is not using local defaults:
psql -h localhost -p 5432 -U postgres -d mydb \
-c 'SELECT current_database(), current_user;'A password prompt may appear. Avoid putting passwords directly in the command because shell history and process listings can expose them.
Run a script file with `-f`
A SQL script is a text file containing one or more SQL statements and, optionally, psql meta-commands. For example, inspect.sql might contain:
\conninfo
\dt public.*
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;Run the file like this:
psql -X -d mydb -f inspect.sqlThe -f option reads commands from the file. The -X option prevents psql from loading your personal psqlrc file. This makes automated output more predictable.
The same file can run against different databases:
psql -X -d staging -f inspect.sql
psql -X -d production -f inspect.sqlMake sure the connected role has permission to read the objects that the script inspects.
Include files from an interactive session
Inside psql, use \i with a path to execute a file:
\i sql/inspect.sqlThe related \ir command resolves a relative path from the directory containing the current script. This is useful when one script includes another:
\ir checks/orders.sqlA script can therefore have a clear entry point:
\ir setup.sql
\ir checks/orders.sql
\ir reports/summary.sqlThe execution flow looks like this:
Check failures in automation
For shell automation, check the exit status after psql runs. A nonzero status indicates failure. You can also make errors stop a script by placing this at its start:
\set ON_ERROR_STOP on
SELECT 1;Without ON_ERROR_STOP, later commands may run after an earlier command failed.
Exercise
Which command runs checks.sql against mydb without loading the user's psqlrc settings?
Show answer
psql -X -d mydb -f checks.sql