Search code examples
bashbitbucketbitbucket-pipelinesbitbucket-cloud

Can "if" statements be used in bitbucket pipelines?


Im trying to run the following step, but it does not execute the "if" steps (lines 5 and 6) (I'm pretty sure they should as the directory tested for does not exist, i tried in multiple formats of bash if, but all of them fails. Is there a way to test for a condition than the one I'm using?

   - step:
      name: Google Cloud SDK Installation
      caches:
        - pip
        - cloudsdk
      script:
        - export ENV=dev
        - source scripts/setenv.sh
        - export CLOUDSDK_CORE_DISABLE_PROMPTS=1
        - SDK_FILENAME=google-cloud-sdk-$SDK_VERSION-linux-x86_64.tar.gz
        - if [ ! -e ${HOME}/google-cloud-sdk ] ; then `curl -O -J https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/${SDK_FILENAME}`; fi
        - if [ ! -e ${HOME}/google-cloud-sdk ] ; then `tar -zxvf ${SDK_FILENAME} --directory ${HOME}`; fi
        - export PATH=${PATH}:${HOME}/google-cloud-sdk/bin
        - GAE_PYTHONPATH=${HOME}/google_appengine
        - export PYTHONPATH=${PYTHONPATH}:${GAE_PYTHONPATH}
        - python scripts/fetch_gae_sdk.py $(dirname "${GAE_PYTHONPATH}")

Solution

  • Basically, Bb Pipelines support conditions, be it file checks using -e or comparisons. For instance, these lines all do work:

    script:
      - '[ ! -e "$BITBUCKET_CLONE_DIR/missing.txt" ] && echo "File does not exist"'
      - 'if [ ! -e "$BITBUCKET_CLONE_DIR/missing.txt" ]; then echo "File does not exist"; fi'
      - if [ ! -e "$BITBUCKET_CLONE_DIR/missing.txt" ]; then echo "File does not exist"; fi
    

    As shown in the example, for some commands it can be needed to wrap the line in single quotes (here, only for demonstration purposes), so if Bb reports a syntax error, you should experiment with that.

    But: are you sure you really want $HOME? By default, you are in $BITBUCKET_CLONE_DIR – not in $HOME –, and therefore the curl call downloads the SDK to $BITBUCKET_CLONE_DIR.