Run step if file exists

Is it possible to check whether a file / directory exists before running a step?

For example, a library might have the ability to create files. A test could be used to check these files, and copy them to a special directory on a mismatch. This directory could then be uploaded as a build artifact. Merely checking for failure() is not sufficient, as not all tests generate a file.

Another use case would be to process a subset of a known set of files (one per step), selected based on the platform being tested. Being able to configure the subset in only one place (where they are created) would be easier to manage, than to use also include it in the strategy params.

A possible workaround could involve the set-env :: command, but that feels quite error-prone.

1 Like

I don’t believe there is any native support for this yet. But with a little bit of shell magic you can make a certain step optional. For example:

steps:
  - name: Only run this if file README exists
run: '(test -f README && echo README exists) || echo README does not exist, skipping step'

This will simply just output the echo on the right if the file does not exist or run the step if it does. Either way, the step will exit “successfully”, not halting your pipeline if the file does not exist.

3 Likes

Your could use https://help.github.com/en/articles/development-tools-for-github-actions#set-an-output-parameter-set-output to have an output from your step that computes the files and this condition a subsiquent step on that output.  And then use the steps context https://help.github.com/en/articles/contexts-and-expression-syntax-for-github-actions#steps-context in the if condition to determine if your step needs to run.  Remember that for outputs to work you must define an id for your step.

2 Likes

ya, this workaround works but ugly, it’d be great if there’s built-in func like fileExists() just like other funcs toJson(), etc.