Search code examples
githubgithub-actions

Check for element in an array in Github action script


I have two arrays defined in a Github action. Target is to check in which array a given element exists.

Problem: When using contains function, Github action seems to compare substrings even in case of array. While this documentation seems to say that it is only the case when searching within string.

My code looks like below:


name: My action

on:
  push:
    branches:
      - '**'

jobs:
  build:

    runs-on: ubuntu-latest
    env:
        JUICE: |
          [
            "apple-juice",
            "orange-juice"
          ]
        FRUIT: |
          [
            "apple",
            "orange"
          ]
          

    - name: check juice
      if: contains(env.JUICE, 'apple')
      run: |
        echo "Found Juice"

    - name: check fruit
      if: contains(env.FRUIT, 'apple')
      run: |
        echo "Found Fruit"

Output: Both check juice and check fruit steps are getting executed. While I expect only check fruit to run.

Is there anyway to achieve this?


Solution

  • I found a way to search for an item with bash array

    name: array check test
    
    on:
      push:
        branches:
          - '**'
    
    jobs:
      build:
    
        runs-on: ubuntu-latest
        env:
            JUICE: |
              (
                "apple-juice"
                "orange-juice"
              )
    
        steps:
        - name: check juice with bash
          run: |
              array=${{ env.JUICE }}
              for item in ${array[*]}
              do
                if [[ "$item" == "apple" ]]; then
                  echo "Found Juice"
                fi
                if [[ "$item" == "apple-juice" ]]; then
                  echo "Found Juice Full Name"
                fi
              done
    

    output: Found Juice Full Name