GitHub Action中如何访问workflow_dispatch定义的输入参数并在脚本中使用
Hey there! Let me walk you through exactly how to access and use those workflow dispatch inputs you’ve defined—whether they’re named with simple keys like logLevel or have spaces like "Which branch do I want to use".
Two Ways to Access Inputs
GitHub automatically makes your workflow dispatch inputs available in two places: injected environment variables, and the github context object. Here’s how to use both:
1. For inputs with simple keys (logLevel, tags)
These are the easiest to work with since their names don’t have spaces.
Using Environment Variables
GitHub converts input names to uppercase, replaces any special characters with underscores, and prefixes them with INPUT_. So:
logLevelbecomesINPUT_LOGLEVELtagsbecomesINPUT_TAGS
You can reference these directly in shell commands:
jobs: your-job-name: runs-on: ubuntu-latest steps: - name: Print log level from env var run: echo "Current log level: $INPUT_LOGLEVEL" - name: Use tags in a command run: echo "Running tests with tags: $INPUT_TAGS"
Using the GitHub Context
You can also pull values directly from the github.event.inputs object using template expressions. This is great if you need to pass the value to actions or use it in conditional logic:
steps: - name: Print log level from context run: echo "Current log level: ${{ github.event.inputs.logLevel }}" - name: Check if tags are provided if: ${{ github.event.inputs.tags != '' }} run: echo "Tags specified: ${{ github.event.inputs.tags }}"
2. For inputs with spaces ("Which branch do I want to use")
Inputs with spaces need a tiny bit of extra care, but it’s still straightforward.
Using Environment Variables
Same rule applies: convert the name to uppercase, replace spaces with underscores, and add the INPUT_ prefix. Your input becomes INPUT_WHICH_BRANCH_DO_I_WANT_TO_USE:
steps: - name: Print target branch from env var run: echo "Using branch: $INPUT_WHICH_BRANCH_DO_I_WANT_TO_USE"
Using the GitHub Context
Since the input name has spaces, you can’t use dot notation—instead, use bracket notation with quotes to reference it:
steps: - name: Print target branch from context run: echo "Using branch: ${{ github.event.inputs['Which branch do I want to use'] }}"
Quick Notes
- If an input is optional (you didn’t set
required: true), make sure to handle cases where the value might be empty (like in the conditional example above). - On Windows runners, environment variables are referenced with
%INPUT_LOGLEVEL%instead of$INPUT_LOGLEVEL, but most workflows use Ubuntu runners so the$syntax is standard. - Both methods work interchangeably—pick whichever feels more readable for your workflow!
内容的提问来源于stack exchange,提问作者Paul




