Stashing Previously Set psql Variables

The command-line based "PostgreSQL interactive terminal" known as psql is handy for manipulating and accessing data in a PostgreSQL database. Because of its command-line nature, psql is particularly well-suited for use in scripts. One of the psql features that makes it even more useful in scripting contexts is its support for "meta-commands." As the psql documentation states, "Anything you enter in psql that begins with an unquoted backslash is a psql meta-command that..." and "...these commands make psql more useful for administration or scripting."

When writing psql scripts, it is often preferable to set some variables locally for the time period that the script is being run but might also be desirable to not change these variables permanently for the psql session if it's likely that other scripts or other work will be performed from the psql session after the script's conclusion. In this post, I will demonstrate use of psql's \set meta-command to temporarily store off previous settings of variables to restore these settings at the script's conclusion.