How to Run GitHub Actions in Another Directory Using Working Directory

How to Run GitHub Actions in Another Directory Using Working Directory

In this blog post, we are going to discuss how to run GitHub Actions in a different directory by using the working-directory option. In some scenarios, you may want to run specific steps of your workflow within a different directory of your project. For example, if you have a mono-repo setup with different projects in separate directories, you might want to build, test, or deploy each project independently within their own directories.

Working Directory in GitHub Actions

The working-directory option in GitHub Actions allows you to define the working directory for a run step. In other words, the command(s) you execute in the run field will be executed in the directory specified by working-directory.

Let’s look at a practical example:

Here’s a breakdown of the steps:

  1. name: Working directory example: This is the name of our workflow. You can replace “Working directory example” with any name you want.
  2. on: [push]: This specifies that the workflow will run on any push event.
  3. jobs:: Here we define our jobs. In this case, we have only one job named build.
  4. runs-on: ubuntu-latest: This specifies that our job will run on the latest version of Ubuntu.
  5. steps:: This is where we define the steps that our job will run.
  6. - name: Checkout code: This is our first step. We are using the actions/checkout@v2 action to checkout our code.
  7. - name: Execute command in another directory: This is our second step where we will execute a command in another directory.
  8. working-directory: ./another-directory: This sets the working directory for the command executed in the run field. Replace ./another-directory with the path to the directory in which you want to execute your command.
  9. run: |: The run keyword is followed by a pipe (|), indicating we’ll be running multiple commands.
  10. echo "This command is run in another directory": This is the command that will be run in the another-directory.

Remember that the path you provide in working-directory should be relative to the root of your repository. Also, the path should exist in your repository; otherwise, you’ll get an error.

Conclusion

The working-directory option in GitHub Actions offers a convenient way to execute steps in a specific directory. This is very useful when dealing with mono-repos or any situation where you need to perform actions in different directories.