1

I try to run shell command in my Bamboo plan. This is my code I try to run:

[ "$(git rev-parse --abbrev-ref HEAD)" == *test* ] || [ "$(git rev-parse --abbrev-ref HEAD)" == *develop* ] && echo "yes"

That should check branch name is test or develop. If it is, then it should print message yes.

I run this on branch develop, then I got error.

Error message: [: develop: unexpected operator


UPDATE:

This is POSIX so based on a post: String comparison in bash. [[: not found I replaced == with a single =.

So my command looks:

[ "$(git rev-parse --abbrev-ref HEAD)" = *test* ] || [ "$(git rev-parse --abbrev-ref HEAD)" = *develop* ] && echo "yes"

Error messaage I got: [: pytest.ini: unexpected operator

No idea what is pytest.ini is doing here. My application using pytest but in this step I didn't run it.

CezarySzulc
  • 1,849
  • 1
  • 14
  • 30

1 Answers1

1

The problem with single brackets is that the wildcards are expanded through the filename expansion (globbing). Consider this:

$ touch test{1,2,3,4}
$ set -x
$ [ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ] || [ "$(git rev-parse --abbrev-ref HEAD)" == *"develop"* ] && echo "yes"
$ [ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ]
++ git rev-parse --abbrev-ref HEAD
+ '[' develop == test1 test2 test3 test4 ']'
-bash: [: too many arguments

If you have double brackets available in your shell, then you might replace single brackets with double brackets:

[[ "$(git rev-parse --abbrev-ref HEAD)" == *"test"* ]] \
    || [[ "$(git rev-parse --abbrev-ref HEAD)" == *"develop"* ]] && echo "yes"

As an alternative, you might use case as follows:

case "$(git rev-parse --abbrev-ref HEAD)" in
    *test*|*develop*)
        echo 'yes'
        ;;
esac

Note, single opening bracket ([) is just a synonym for the test builtin with the only exception that the single opening bracket requires the last argument to be ].

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60