Wednesday, October 26, 2022

[SOLVED] Sql in bash script (postgres)

Issue

i have a command in bash script for rename base. It's work, example

psql -U $User -t -A -q -c 'ALTER DATABASE "Old_Name" RENAME TO "New_Name"'

But if i do this -

O_Name='Old_Name'

N_Name='New_Name'

psql -U $User -t -A -q -c 'ALTER DATABASE "$O_Name" RENAME TO "$N_Name"'

It's not work, i think sql get $O_Name not Old_Name. How to pass the value of a variable bash to sql?


Solution

Single quotes don't allow for environment variable expansion. Use double quotes instead (and escape the nested quotes). Like,

psql -U $User -t -A -q -c "ALTER DATABASE \"$O_Name\" RENAME TO \"$N_Name\""


Answered By - Elliott Frisch
Answer Checked By - Cary Denson (WPSolving Admin)