Home > Software design >  Concatenate connection string
Concatenate connection string

Time:10-22

This connection string works for psql:

psql "password='${INPUT_PASSWORD}' dbname=analytics host='${INPUT_HOST}' user=analytics port=32648"

I want to make it more readable, tried:

psql "password='${INPUT_PASSWORD}'"  
     "dbname=analytics"  
     "host='${INPUT_HOST}'"  
     "user=analytics"  
     "port=32648"

Gives "error: could not connect to server: No such file or directory"

Then tried:

psql "password='${INPUT_PASSWORD}'" \
     "dbname=analytics" \
     "host='${INPUT_HOST}'" \
     "user=analytics" \
     "port=32648"

Which gives the same error.

Is there a way that I can split the string onto multiple lines and still have it accepted as a connection string by Postgres?

CodePudding user response:

The problem with your second attempt is that you inject unquoted whitespace between each argument and its following backslash. Since the spaces are intended to be in the argument, they need to be quoted as well.

psql "password='${INPUT_PASSWORD}' "\
     "dbname=analytics "\
     "host='${INPUT_HOST}' "\
     "user=analytics "\
     "port=32648"

Using bash, I would define an array instead, and let array parameter expansion insert the spaces.

psql_args=(
    "password='$INPUT_PASSWORD'"
    dbname=analytics
    "host='${INPUT_HOST}'"
    user=analytics
    port=32648
)

psql "${psql_args[*]}"

(Actually, since you appear to be constructing the conninfo string yourself, rather than receiving it via some other configuration file, I would probably use the options to specify each piece of information instead.)

CodePudding user response:

Why not just:

psql "password='${INPUT_PASSWORD}'
      dbname=analytics
      host='${INPUT_HOST}'
      user=analytics
      port=32648"

(as answer, because you cannot do multi-line in the comments)

  •  Tags:  
  • bash
  • Related