K
K
kos212021-04-29 18:58:21
PostgreSQL
kos21, 2021-04-29 18:58:21

PostgreSQL: how to wait for password input when running script?

Task: ask the user for a password and execute the necessary commands.
Here is my batch file:

@echo on
"C:\Program Files\PostgreSQL\13\bin\psql.exe" -U postgres -f  D:/script.sql -a
pause

If I enter a wrong password, it just goes through the script
608ad6fa71003248597490.png
. How can I make it wait for the correct password?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Akina, 2021-04-30
@kos21

First ask for a password in a variable, and then run it by passing the password from the variable.

@echo off
cls
SET /P psqlpassword="Введите пароль (Enter для завершения): "
if "%psqlpassword%"=="" exit /b
"C:\Program Files\PostgreSQL\13\bin\psql.exe" -U postgres -W %psqlpassword% -f  D:/script.sql -a 
pause

If the password is incorrect, an error message will be displayed and execution will continue.
If you need to re-request the password, you should use error checking:
@echo off
:execute_psql
cls
SET /P psqlpassword="Введите пароль (Enter для завершения): "
if "%psqlpassword%"=="" exit /b
"C:\Program Files\PostgreSQL\13\bin\psql.exe" -U postgres -W %psqlpassword% -f  D:/script.sql -a 
if errorlevel 1 goto :execute_psql
pause

True, you need to make sure that psql.exe returns it, which is not a fact. You should also make sure that it does not return errors in other situations when a second password request and start are not required, or enter a check for an error code.

K
ky0, 2021-04-29
@ky0

And why do you enter the password with your hands, especially the wrong one? Take it from the pgpass file or just specify it as a PGPASSWORD variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question