Skip to content
shellhacks.dev
Databases

Output without headers or alignment

Get bare values from psql for a script with -At, which turns off the headers, the alignment and the row count so a single value can be captured.

1 min read
Summarize in AI

A shell script needs one number out of a query, without the header, the dashes or the row count.

Shell
psql -c "SELECT count(*) FROM pg_database"
echo ---
n=$(psql -At -c "SELECT count(*) FROM pg_database")
echo "databases: $n"
psql -At -F ',' -c "SELECT datname, encoding FROM pg_database ORDER BY 1 LIMIT 2"
Text
 count
-------
     3
(1 row)

---
databases: 3
postgres,6
template0,6

-A selects unaligned output and -t prints tuples only, so no header, no footer and no padding, as the psql reference lists. Together they leave one line per row, which a command substitution can capture. -F changes the field separator from the pipe to a comma. The first command shows the default format that would otherwise have to be parsed.

A value that contains the separator or a newline is not escaped, so use --csv for text columns. Add -X to skip the user's .psqlrc, which can add formatting to the output of a script. An empty result gives an empty string, and -q removes notices such as the command tag from INSERT statements.

Share

More snippets

Databases

Dump one table

Dump one table with pg_dump -t name. The option takes a pattern, so -t orders does not match orders_archive but -t 'orders*' does, and quoting rules apply.

2 min read
Databases

Run SQL from a file

Run SQL from a file with psql -f. An error in the middle does not stop the file and the exit status stays 0, unless ON_ERROR_STOP is set to 1.

2 min read
Databases

Describe a table

Show a table's columns, indexes and foreign keys with the psql meta-command backslash d, and add a plus sign for storage and comments.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.