Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to set environment variable and execute command in one line

I want to make a backup with PostGreSQL pg_dump command with command line like :

"<c:\Program Files\PostgreSQL\9.6\bin\pg_dump>" -h localhost -p 5432 -d test_backup_bat -U user -f D:\destination_backup\test.backup

but I need to set PGPASSWORD before as environment variable to execute the backup command

PGPASSWORD=mypassword

How can I make this in only one command line into Windows CLI ?

like image 524
Florian JOLIVET Avatar asked Oct 16 '25 10:10

Florian JOLIVET


1 Answers

Setting a variable and using it inside the same line in a batch file or a command line can be "tricky" as the full line/command is parsed before the variable is set.

BUT, in your case, you don't need to do anything special because you don't need to use the variable in the command except for setting it. The pg_dump just reads the contents of the environment variable from its own environment block that is inherited from the parent cmd process. If the parent process has the variable defined, then pg_dump can read it from its own copy.

So, you just need two commands (one to set the variable and one to start the new process) inside the same line, executed one after the other. This is done with the & operator:

set "PGPASSWORD=myPassword" & "c:\Program Files\PostgreSQL\9.6\bin\pg_dump" -h localhost -p 5432 -d test_backup_bat -U user -f D:\destination_backup\test.backup
like image 196
MC ND Avatar answered Oct 19 '25 00:10

MC ND