Pull Request Decoration with Bitbucket Server and Bamboo

Hi, how did you get around this failing on the master branch when the PR variables are no longer available? I am a bit stuck. I create a plan branch when a PR is created and insert the required variables from bamboo in the sonar properties file which are needed for PR decoration but when any other branch runs those variables do not exist and the build fails.
I have this in a script:

echo "sonar.pullrequest.branch=${bamboo.repository.pr.sourceBranch}" >> $HOME/sonar-scanner/conf/sonar-scanner.properties

echo "sonar.pullrequest.key=${bamboo.repository.pr.key}" >> $HOME/sonar-scanner/conf/sonar-scanner.properties

echo "sonar.pullrequest.base=${bamboo.repository.pr.targetBranch}" >> $HOME/sonar-scanner/conf/sonar-scanner.properties

Regards,
Ian