Search code examples
bashcommand-line-interfacegithub-actionscicd

GitHub Actions can't read `while (( "$#" ));` in .bash script


Given a GitHub Action file:

name: Pull Request

on:
  pull_request:
    branches: [main]
    types: [opened, reopened, ready_for_review]

jobs:
  build_and_test:
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v3

      - name: Run bash script
        run: |
          sh build.bash --a 3 --b 4

I'm unable to run the following build.bash file through GitHub Actions, instead getting the error build.bash: 17: 4: not found where line 17 corresponds with the line: while (( "$#" ));

#!/bin/sh
REPO_NAME="my-repo"

# Set defaults up top for clarity and define only once
A="1"
B="2"

usage()
{
    echo "Usage: build.sh [--a version] [--b version]"
    echo ""
    echo "--a 'a' version to use. Defaults to $A."
    echo "--b 'b' version to use. Defaults to $B"
    exit 1
}

while (( "$#" ));
do
    case "$1" in
        -h|--help)
            usage
        ;;

        --a)
            shift
            A="$1"
            shift
        ;;

        --b)
            shift
            B="$1"
            shift
        ;;

        # Unknown option
        *)
            echo "Unrecognized option: $1"
            usage
        ;;
    esac
done



echo CLI args: --a=$A --b=$B

When ran locally, everything prints out as expected:

sh build.bash --a 3 --b 4
# CLI args: --a=3 --b=4

How do I ensure that running the same command in GitHub Actions returns the same value while maintaining a similar logic for parsing CLI arguments


Solution

  • The issue resolves if we run bash build.bash --a 3 --b 4 instead of sh build.bash --a 3 --b 4 in the GHA .yml file. Correspondingly, we should update the shebang with #! /bin/bash at the top of the .bash file.

    Shoutout to @GordonDavisson and @DiegoTorresMilano for helping resolve this issue