GitHub Actions: Executing Scripts and Inline Commands in a Workflow

GitHub Actions: Executing Scripts and Inline Commands in a Workflow

Hello, GitHub enthusiasts! As we continue exploring the world of GitHub Actions, today we focus on a topic that’s particularly exciting: executing scripts and inline commands in your workflows.

Running Inline Commands

One of the most straightforward ways of running code in GitHub Actions is writing inline commands within the run key of your workflow file. You can run shell commands directly using the run keyword. For example:

In this example, the run command executes the shell command echo, printing the string “Hello, World!” to the console.

Inline commands are very convenient for simple operations or when the number of commands to be executed is small.

Executing Multi-line Scripts

For complex operations involving multiple commands, multi-line scripts are very useful. To write a multi-line script, simply start a new line after the run keyword and indent your code:

In this case, the workflow runs two separate echo commands. The pipe | symbol indicates that the following indented lines should be treated as a multi-line string.

Running External Scripts

For even more complex operations, you may want to use an external script. This is particularly useful when you have a long script or when you want to reuse the script in multiple workflows or jobs.

To use an external script, you need to first check out your repository’s code using the actions/checkout@v2 action. Then, you can execute the script with a shell command.

In this case, script.sh is a bash script located at the root of the repository.

Important: If your script relies on certain environment variables, remember to set these in your workflow file.

Using Environment Variables in Scripts

You can access environment variables directly from your scripts. For instance, consider the following step where an environment variable is defined:

In your script.sh, you can use this variable like so:

In this case, the script would output “Hello, World!” when run.

Conclusion

GitHub Actions provide a versatile platform for automating software workflows, and running scripts and commands is at the core of this process. Whether you choose to run inline commands, multi-line scripts, or external scripts depends on the complexity of your tasks and your personal preference.

Remember, mastering these fundamentals is key to unlocking the full potential of GitHub Actions. Happy coding!