GitHub Actions can be used to do something whenever something happens in one of your GitHub repositories. If you are not familiar with GitHub Actions, check out my article Getting Started with GitHub Actions.
For example, let's say you have a repository named my-repo that contains 2 files, foo.jpg and bar.jpg, perhaps like this.
- https://github.com/JohnDoe/my-repo/blob/main/images/foo.jpg
- https://github.com/JohnDoe/my-repo/blob/main/images/bar.jpg
The ${{ github.workspace }} variable can be used to list the files in your repository.
name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
push:
branches:
- main
jobs:
github-action-job:
runs-on: ubuntu-latest
steps:
- name: Checking out the repository code . . .
uses: actions/checkout@v4
- name: List files in the repository
run: |
ls ${{ github.workspace }}
And here is example of how to list all changed files using tj-actions/changed-files
name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
push:
branches:
- main
jobs:
github-action-job:
runs-on: ubuntu-latest
steps:
- name: Checking out the repository code . . .
uses: actions/checkout@v4
- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v40
- name: List all changed files
run: |
for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
echo "$file was changed"
done
Often, there will be certain files you'll want to ignore, such as README.md and files in the .github/workflows directory. Files can be ignored by including files_ignore.
jobs:
get_changed_files:
runs-on: ubuntu-latest
steps:
- name: Checking out the repository code
uses: actions/checkout@v4
- name: Get changed files excluding README.md and files in the .github/workflows directory
id: changed-files
uses: tj-actions/changed-files@v40
with:
separator: ","
files_ignore: |
README.md
.github/workflows/*
- name: changed files
run: |
echo "changed files = ${{ steps.changed-files.outputs.all_changed_files }}"
- name: changed files count
run: |
echo "changed files count = ${{ steps.changed-files.outputs.all_changed_files_count }}"
outputs:
changed_files_count: ${{ steps.changed-files.outputs.all_changed_files_count }}
Which should return something like this.
And here is how to get the changed files as JSON.
name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
push:
branches:
- main
jobs:
github-action-job:
runs-on: ubuntu-latest
steps:
- name: Checking out the repository code . . .
uses: actions/checkout@v4
- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v40
with:
json: true
escape_json: true
- name: List all changed files as escaped JSON
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
Which should output something like this.
echo 'files = ["path/to/foo.txt"]["path/to/bar.txt"]
Did you find this article helpful?
If so, consider buying me a coffee over at