Escaping hyphen in yaml key value pair

# .travis.yml

before_script:
  - bundle exec rake lint
  - "psql -c 'create database authentication-server_test;' -U postgres"

language: ruby

services:
  - postgresql

I get:

$ psql -c 'create database authentication-server_test;' -U postgres
ERROR:  syntax error at or near "-"
LINE 1: create database authentication-server_test;

I’ve done a fair bit of googling and have not found anything…

Reading your .travis.yml, it seems like the issue here is your PostgreSQL identifier:

authentication-server_test

This needs to be quoted so that PostgreSQL won’t try to interpret the - as an operator. Identifiers are quoted with double quotes so you need to this:

"authentication-server_test"

Into the Postgres database. You could escape the double quotes in .travis.yml by doing the following:

before_script:
  - bundle exec rake lint
  - "psql -c 'create database \"authentication-server_test\";' -U postgres"

Second option would be to drop the outer double quotes (the YAML quotes for the string) while adding the inner double quotes (for the Postgres identifier):

before_script:
  - bundle exec rake lint
  - psql -c 'create database "authentication-server_test";' -U postgres

Thirdly, switch to createdb about avoid the problem altogether:

before_script:
  - bundle exec rake lint
  - createdb authentication-server_test -U postgres

Thus, only having to worry about the shell’s and YAML’s quoting needs (neither of which apply here).

1 Like