Running script conditionally does not work in travis.yml, why?

user1283776 picture user1283776 · Aug 5, 2016 · Viewed 10.6k times · Source

The following causes travis to not build at all. When I try to validate the travis.yml file, it complains that the line just above the if statement is missing a - character at column 3, but the error has to do with the if statement below.

Do I have to move the if statement out to a script?

# Deploy
after_success:
  - ./tools/docker-push-container.sh
  - if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then
      ./.travis/success_message.sh
    fi

Answer

larsks picture larsks · Aug 5, 2016

You're making some assumptions about YAML syntax that are causing you problems. If you "exend" a line of YAML by indenting subsequent lines, like this:

- The quick brown fox
  jumped over the
  lazy dog.

It is exactly like you instead wrote this:

- The quick brown fox jumped over the lazy dog.

This means that your shell fragment, which you've written as:

  - if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then
      ./.travis/success_message.sh
    fi

Actually becomes:

if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then ./.travis/success_message.sh fi

And if you try run that line in the shell, you get:

sh: -c: line 1: syntax error: unexpected end of file

If you want to include a multi-line shell script in your YAML document, your best bet is probably to use the verbatim block operator, |, like this:

  - |
    if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then
      ./.travis/success_message.sh
    fi

Which will result, as intended, in:

if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then
  ./.travis/success_message.sh
fi

Alternatively, you could just make proper use of semicolons:

  - if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then
      ./.travis/success_message.sh;
    fi

Note the new ; before the terminal fi. This results in:

if [ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]; then ./.travis/success_message.sh; fi

...which is perfectly valid shell syntax.