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.
A shell script needs one number out of a query, without the header, the dashes or the row count.
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" 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.