Skip to main content

此版本的 GitHub Enterprise 已停止服务 2022-10-12. 即使针对重大安全问题,也不会发布补丁。 为了获得更好的性能、更高的安全性和新功能,请升级到最新版本的 GitHub Enterprise。 如需升级帮助,请联系 GitHub Enterprise 支持

Expressions

You can evaluate expressions in workflows and actions.

注意:GitHub Enterprise Server 目前不支持 GitHub 托管的运行器。 可以在 GitHub public roadmap 上查看有关未来支持计划的更多信息。

About expressions

You can use expressions to programmatically set environment variables in workflow files and access contexts. An expression can be any combination of literal values, references to a context, or functions. You can combine literals, context references, and functions using operators. For more information about contexts, see "Contexts."

Expressions are commonly used with the conditional if keyword in a workflow file to determine whether a step should run. When an if conditional is true, the step will run.

You need to use specific syntax to tell GitHub to evaluate an expression rather than treat it as a string.

${{ <expression> }}

if 条件下使用表达式时,可以省略表达式语法 (${{ }}),� 为 GitHub 会自动将 if 条件作为表达式求值。 For more information about if conditionals, see "Workflow syntax for GitHub Actions."

警告:创建工作流程和操作时,应始终考虑代� �是否会执行来自可能的攻击者的不信任输入。 某些上下文应被视为不受信任的输入,� 为攻击者可能会插入自己的恶意内容。 有关详细信息,请参阅“了解脚本注入的风险”。

Example expression in an if conditional

steps:
  - uses: actions/hello-world-javascript-action@v1.1
    if: ${{ <expression> }}

Example setting an environment variable

env:
  MY_ENV_VAR: ${{ <expression> }}

Literals

As part of an expression, you can use boolean, null, number, or string data types.

Data typeLiteral value
booleantrue or false
nullnull
numberAny number format supported by JSON.
stringYou don't need to enclose strings in ${{ and }}. However, if you do, you must use single quotes (') around the string. To use a literal single quote, escape the literal single quote using an additional single quote (''). Wrapping with double quotes (") will throw an error.

Example

env:
  myNull: ${{ null }}
  myBoolean: ${{ false }}
  myIntegerNumber: ${{ 711 }}
  myFloatNumber: ${{ -9.2 }}
  myHexNumber: ${{ 0xff }}
  myExponentialNumber: ${{ -2.99e-2 }}
  myString: Mona the Octocat
  myStringInBraces: ${{ 'It''s open source!' }}

Operators

OperatorDescription
( )Logical grouping
[ ]Index
.Property de-reference
!Not
<Less than
<=Less than or equal
>Greater than
>=Greater than or equal
==Equal
!=Not equal
&&And
||Or

GitHub performs loose equality comparisons.

  • If the types do not match, GitHub coerces the type to a number. GitHub casts data types to a number using these conversions:

    TypeResult
    Null0
    Booleantrue returns 1
    false returns 0
    StringParsed from any legal JSON number format, otherwise NaN.
    Note: empty string returns 0.
    ArrayNaN
    ObjectNaN
  • A comparison of one NaN to another NaN does not result in true. For more information, see the "NaN Mozilla docs."

  • GitHub ignores case when comparing strings.

  • Objects and arrays are only considered equal when they are the same instance.

Functions

GitHub offers a set of built-in functions that you can use in expressions. Some functions cast values to a string to perform comparisons. GitHub casts data types to a string using these conversions:

TypeResult
Null''
Boolean'true' or 'false'
NumberDecimal format, exponential for large numbers
ArrayArrays are not converted to a string
ObjectObjects are not converted to a string

contains

contains( search, item )

Returns true if search contains item. If search is an array, this function returns true if the item is an element in the array. If search is a string, this function returns true if the item is a substring of search. This function is not case sensitive. Casts values to a string.

Example using a string

contains('Hello world', 'llo') returns true.

Example using an object filter

contains(github.event.issue.labels.*.name, 'bug') returns true if the issue related to the event has a label "bug".

For more information, see "Object filters."

Example matching an array of strings

Instead of writing github.event_name == "push" || github.event_name == "pull_request", you can use contains() with fromJson() to check if an array of strings contains an item.

For example, contains(fromJson('["push", "pull_request"]'), github.event_name) returns true if github.event_name is "push" or "pull_request".

startsWith

startsWith( searchString, searchValue )

Returns true when searchString starts with searchValue. This function is not case sensitive. Casts values to a string.

Example

startsWith('Hello world', 'He') returns true.

endsWith

endsWith( searchString, searchValue )

Returns true if searchString ends with searchValue. This function is not case sensitive. Casts values to a string.

Example

endsWith('Hello world', 'ld') returns true.

format

format( string, replaceValue0, replaceValue1, ..., replaceValueN)

Replaces values in the string, with the variable replaceValueN. Variables in the string are specified using the {N} syntax, where N is an integer. You must specify at least one replaceValue and string. There is no maximum for the number of variables (replaceValueN) you can use. Escape curly braces using double braces.

Example

format('Hello {0} {1} {2}', 'Mona', 'the', 'Octocat')

Returns 'Hello Mona the Octocat'.

Example escaping braces

format('{{Hello {0} {1} {2}!}}', 'Mona', 'the', 'Octocat')

Returns '{Hello Mona the Octocat!}'.

join

join( array, optionalSeparator )

The value for array can be an array or a string. All values in array are concatenated into a string. If you provide optionalSeparator, it is inserted between the concatenated values. Otherwise, the default separator , is used. Casts values to a string.

Example

join(github.event.issue.labels.*.name, ', ') may return 'bug, help wanted'

toJSON

toJSON(value)

Returns a pretty-print JSON representation of value. You can use this function to debug the information provided in contexts.

Example

toJSON(job) might return { "status": "Success" }

fromJSON

fromJSON(value)

Returns a JSON object or JSON data type for value. You can use this function to provide a JSON object as an evaluated expression or to convert environment variables from a string.

Example returning a JSON object

This workflow sets a JSON matrix in one job, and passes it to the next job using an output and fromJSON.

name: build
on: push
jobs:
  job1:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
      - id: set-matrix
        run: echo "::set-output name=matrix::{\"include\":[{\"project\":\"foo\",\"config\":\"Debug\"},{\"project\":\"bar\",\"config\":\"Release\"}]}"
  job2:
    needs: job1
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{ fromJSON(needs.job1.outputs.matrix) }}
    steps:
      - run: build

Example returning a JSON data type

This workflow uses fromJSON to convert environment variables from a string to a Boolean or integer.

name: print
on: push
env:
  continue: true
  time: 3
jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - continue-on-error: ${{ fromJSON(env.continue) }}
        timeout-minutes: ${{ fromJSON(env.time) }}
        run: echo ...

hashFiles

hashFiles(path)

Returns a single hash for the set of files that matches the path pattern. You can provide a single path pattern or multiple path patterns separated by commas. The path is relative to the GITHUB_WORKSPACE directory and can only include files inside of the GITHUB_WORKSPACE. This function calculates an individual SHA-256 hash for each matched file, and then uses those hashes to calculate a final SHA-256 hash for the set of files. If the path pattern does not match any files, this returns an empty string. For more information about SHA-256, see "SHA-2."

You can use pattern matching characters to match file names. Pattern matching is case-insensitive on Windows. For more information about supported pattern matching characters, see "Workflow syntax for GitHub Actions."

Example with a single pattern

Matches any package-lock.json file in the repository.

hashFiles('**/package-lock.json')

Example with multiple patterns

Creates a hash for any package-lock.json and Gemfile.lock files in the repository.

hashFiles('**/package-lock.json', '**/Gemfile.lock')

Check Functions

You can use the following status check functions as expressions in if conditionals. A default status check of success() is applied unless you include one of these functions. For more information about if conditionals, see "Workflow syntax for GitHub Actions".

success

Returns true when none of the previous steps have failed or been canceled.

Example

steps:
  ...
  - name: The job has succeeded
    if: ${{ success() }}

always

Causes the step to always execute, and returns true, even when canceled. A job or step will not run when a critical failure prevents the task from running. For example, if getting sources failed.

Example

if: ${{ always() }}

cancelled

Returns true if the workflow was canceled.

Example

if: ${{ cancelled() }}

failure

Returns true when any previous step of a job fails. If you have a chain of dependent jobs, failure() returns true if any ancestor job fails.

Example

steps:
  ...
  - name: The job has failed
    if: ${{ failure() }}

failure with conditions

You can include extra conditions for a step to run after a failure, but you must still include failure() to override the default status check of success() that is automatically applied to if conditions that don't contain a status check function.

Example
steps:
  ...
  - name: Failing step
    id: demo
    run: exit 1
  - name: The demo step has failed
    if: ${{ failure() && steps.demo.conclusion == 'failure' }}

Object filters

You can use the * syntax to apply a filter and select matching items in a collection.

For example, consider an array of objects named fruits.

[
  { "name": "apple", "quantity": 1 },
  { "name": "orange", "quantity": 2 },
  { "name": "pear", "quantity": 1 }
]

The filter fruits.*.name returns the array [ "apple", "orange", "pear" ].

You may also use the * syntax on an object. For example, suppose you have an object named vegetables.


{
  "scallions":
  {
    "colors": ["green", "white", "red"],
    "ediblePortions": ["roots", "stalks"],
  },
  "beets":
  {
    "colors": ["purple", "red", "gold", "white", "pink"],
    "ediblePortions": ["roots", "stems", "leaves"],
  },
  "artichokes":
  {
    "colors": ["green", "purple", "red", "black"],
    "ediblePortions": ["hearts", "stems", "leaves"],
  },
}

The filter vegetables.*.ediblePortions could evaluate to:


[
  ["roots", "stalks"],
  ["hearts", "stems", "leaves"],
  ["roots", "stems", "leaves"],
]

Since objects don't preserve order, the order of the output can not be guaranteed.