diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml index 8ef5387..c76fe60 100644 --- a/doc/src/sgml/ref/psql-ref.sgml +++ b/doc/src/sgml/ref/psql-ref.sgml @@ -2236,6 +2236,24 @@ lo_import 152801 + \setenv [ name [ value ] ] + + + + Sets the environment variable name to value, or if the + value is + not supplied, unsets the environment variable. Example: + +foo=> \setenv PAGER less +foo=> \setenv LESS -imx4F + + + + + + \sf[+] function_description diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index 2c38902..797317a 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -1104,6 +1104,50 @@ exec_command(const char *cmd, free(opt0); } + + /* \setenv -- set environment command */ + else if (strcmp(cmd, "setenv") == 0) + { + char *envvar = psql_scan_slash_option(scan_state, + OT_NORMAL, NULL, false); + char *envval = psql_scan_slash_option(scan_state, + OT_NORMAL, NULL, false); + + if (!envvar) + { + psql_error("\\%s: missing required argument\n", cmd); + success = false; + } + else if (!envval) + { + /* No argument - unset the environment variable */ + unsetenv(envvar); + success = true; + } + else + { + /* Set variable to the vakue of the next argument */ + int len = strlen(envvar) + strlen(envval) + 1; + char *newval = malloc(len + 1); + + if (!newval) + { + psql_error("out of memory\n"); + exit(EXIT_FAILURE); + } + snprintf(newval, len+1, "%s=%s", envvar, envval); + putenv(newval); + success = true; + /* + * Do not free newval here, it will screw up the environment + * if you do. See putenv man page for details. That means we + * leak a bit of memory here, but not enough to worry about. + */ + } + free(envvar); + free(envval); + } + /* \sf -- show a function's source code */ else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0) {