Tuesday, November 16, 2021

[SOLVED] psql: FATAL: role "-h" does not exist

Issue

I have been searching for this issue online and none of the answers clarify my question.

Here is my issue:

I am trying to run .sql files using one of the scripts(abc.sh) in Centos(SSH). These .sql files runs the select commands on postgreSQL and retrieve the data into a file. However, when I am trying to run the script(abc.sh) I see an error thrown on console as below

-bash: line 2: <**environment-file-path**>: Permission denied
psql: FATAL:  role "-h" does not exist

The error is occurred on the line

. /<env_file_path>/yyy.env
export PGPASSWORD=$PGPASSWORD | psql -U $PGUSERNAME $PGNAME -h $PGHOST -c "SET search_path TO xxx;COPY (select....,

I am really not sure what is causing the issue here as i did whatever can be done from my end. 1. I have executed the same scripts in different environment with different host and user credentials and it worked. 2. I have changed the pg_hba.conf file i.e. I made it to look alike as of the environment in which the scripts ran successfully.

NOTE: I have an environment file which stores all the useful information and parameters for the above variables(second snippet) are passed from this env file.

Even after doing this stuff i don't see any change on the issue. Hopefully, this is a minor issue and can be fixed easily with someone's help.


Solution

You need to make the file /<env_file_path>/yyy.env readable It looks like the directory that contains that file is missing execute permission. execute is needed to read files in that directory.

but there's some really bad shell scripting there... always use quotes around variables. also don't pipe export.

export PGPASSWORD="$PGPASSWORD" 
psql -U "$PGUSERNAME" "$PGNAME" -h "$PGHOST" -c "SET search_path TO xxx;COPY (select....,  "

Now you will get a more sensible error message when you forget to set $PGNAME.

Always use quotes, if you come across a use case for not having quotes you should probably be using an array there (and still using quotes).



Answered By - Jasen