8

I am trying to execute a non-interactive postgres command.

PGPASSWORD=$PGPASS psql -h 127.0.0.1 -U postgresql -d $PGDB --command "select count(*) from services"

Which has been giving me this response.

psql: warning: extra command-line argument "from" ignored

psql: warning: extra command-line argument "services;" ignored

psql: warning: extra command-line argument "mydbname" ignored

psql: FATAL: database "count(*)" does not exist

I've read that this could be because the terminal / bash is trying to break up each argument to --command / -c as it's own argument.

I've also tried this:

PSQLARGS=(-h 127.0.0.1 -U postgresql -c )
PSQLARGS+=("select count(*) from services;")
PSQLARGS+=(${PGDB})
PGPASSWORD=$PGPASS psql "${PSQLARGS[@]}"

Some way of forcing the terminal to know it's one argument, this also didn't work.

Community
  • 1
  • 1
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Writing `$PGDB` or `$PGPASS` is unsafe because of https://stackoverflow.com/questions/5819423/bash-variables-with-spaces but aside from that, this command line looks like it can't produce these error messages. Can you provide a reproducible test case? – Daniel Vérité Jun 21 '19 at 18:29
  • 1
    @ThomasReggi I'm having the same exact problem. Ever get any solution to this? – MikeyE Oct 09 '19 at 17:17
  • @MikeyE Check out my solution below and let me know if it works for you: https://stackoverflow.com/a/60263058/178728 – stratis Feb 17 '20 at 13:03

2 Answers2

7

This is a pretty cheap and common error. Putting everything in quotes should do the trick.

Try this:

PGPASSWORD="$PGPASS" psql -h '127.0.0.1' -U 'postgresql' -d "$PGDB" --command "select count(*) from services"

Let us know if it works for you.

stratis
  • 7,750
  • 13
  • 53
  • 94
1

It looks to me like $PGDB is empty, so psql thinks --command is the name of the database.

Jeremy
  • 6,313
  • 17
  • 20
  • This is not the case. I've logged out `$PGDB` and placed `-d $PGDB` at different parts of the command, as well as just having `$PGDB` at the end. Nothing is working. – ThomasReggi Jun 21 '19 at 17:04
  • Interesting. What shell are you using? bash? – Jeremy Jun 21 '19 at 17:16