0

I want to execute a command on a remote server (Cent OS 7) and use the environment variables defined on that server. However, when I run this command

ssh [email protected] "PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c 'COPY myapp_currencyprice to STDOUT WITH (DELIMITER \",\", FORMAT CSV, HEADER)' > /tmp/prices.csv"

it seems the command is trying to use "$DB_PASS" and other env vars from the localhost instead of from "remotehost.com". What's the proper way to reference env vars from the remote server?

7
  • Try to escape the $-signs to prevent local expansion. Commented Dec 11, 2021 at 20:29
  • @RudiC that's an answer: please post it as an answer and not a comment. Posting answers in comments is actively harmful since people cannot vote on them, so it circumvents the normal quality control processes of the site, and they can also discourage others from posting the solution as a proper answer meaning the question can remain unanswered for ever. Commented Dec 11, 2021 at 21:02
  • @roaima see above. Commented Dec 11, 2021 at 21:03
  • @RudiC, Tried '"PGPASSWORD=\$DB_PASS' but this didn't work. Commented Dec 11, 2021 at 21:12
  • @roaima, can you post the command that you mean? The issue is I already have single quotes in the expression itself. I tried to escape them with "\'" but that didn't work. Commented Dec 11, 2021 at 21:16

2 Answers 2

2

You need to use single quotes to stop the local shell getting at the string:

ssh [email protected] 'stuff here...'

You then need to swap the internal quotes around:

ssh [email protected] 'PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c "COPY myapp_currencyprice to STDOUT WITH (DELIMITER \",\", FORMAT CSV, HEADER)" > /tmp/prices.csv'

However, this still won't work because your .bash_profile won't be included as you aren't using an interactive shell. At this point the most obvious solution is to include it explicitly:

ssh [email protected] '. .bash_profile; PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c "COPY myapp_currencyprice to STDOUT WITH (DELIMITER \",\", FORMAT CSV, HEADER)" > /tmp/prices.csv'

You may want to look up these two references to understand the difference between the different types of quotes

0

(Comment converted to an answer, as proposed by terdon...)

Try to escape the $-signs to prevent local expansion. Like

"PGPASSWORD=\$DB_PASS psql -U \$DB_USER -d $DB_NAME ..."

What exactly did not work, as alluded to in your comment? Did you also enclose the command in single quotes? Don't, select either.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.