Saving The Output From psql

 
Occasionally, you will need to capture data when working with a database. You can cut-n-paste or use a shell command like script. In typical PostgreSQL fashion, psql has two ways to save your output.

The First Way

You must invoke psql with the --log-file-<filename> or -L <filename> option. The entire session will be recorded.

stoker@ThinkPad:~$ psql --log-file=/tmp/psqllog demo
Password for user stoker:
psql (17.4 (Ubuntu 17.4-1.pgdg24.04+2))
Type "help" for help.
demo=# \d ledger
                   Table "public.ledger"
     Column     |  Type   | Collation | Nullable | Default
----------------+---------+-----------+----------+---------
 id             | integer |           |          |
 tx_id          | integer |           |          |
 total_register | money   |           |          |
 misc           | integer |           |          |
 status         | text    |           |          |
demo=# \q
stoker@ThinkPad:~$ cat /tmp/psqllog
                   Table "public.ledger"
     Column     |  Type   | Collation | Nullable | Default
----------------+---------+-----------+----------+---------
 id             | integer |           |          |
 tx_id          | integer |           |          |
 total_register | money   |           |          |

The Second Way

The other choice is to use -o <file> or --output=<filename> when you start psql. The differences are that the SQL command is not recorded

and the output does not show on your screen.

stoker@ThinkPad:~$ psql -o /tmp/out demo
Password for user stoker:
psql (17.4 (Ubuntu 17.4-1.pgdg24.04+2))
Type "help" for help.
demo=# \dt         # note the lack of output compared to the above
demo=# \q
stoker@ThinkPad:~$ cat /tmp/out
          List of relations
 Schema |   Name    | Type  | Owner
--------+-----------+-------+--------
 public | customers | table | stoker
 public | ex01      | table | stoker
 public | ex02      | table | stoker
 public | ex03      | table | stoker
 public | foo       | table | stoker
 public | ledger    | table | stoker
 public | register  | table | stoker
 public | two       | table | stoker
 public | v         | table | stoker
 public | z         | table | stoker
 public | zz        | table | stoker
(11 rows)

Summary

These two little options can save you a lot of grief when you need to save the output from psql.  You will find them very handy every so often.

Comments

Popular posts from this blog

Can Artificial Intelligence Created Better Tables Than You?

How PostgreSQL's Aggregate FILTER Will Spoil You

PostgreSQL's COPY and \COPY