Running Multiple Commands in a Subdirectory with Makefile

Learn how to run multiple commands within a subdirectory in a Makefile. By binding commands together using &&, you can ensure they execute in the same shell instance, allowing for more efficient task automation. Discover practical examples to enhance your Makefile usage.

Running Multiple Commands in a Subdirectory with Makefile

In our project, we use a Makefile to automate tasks. Sometimes, we need to execute commands within a subdirectory and run multiple commands sequentially. This article demonstrates how to achieve this in a Makefile.

Problem

By default, commands in a Makefile execute in the directory where the Makefile is located. Consider the following example:

list:
    pwd
    cd ~/Downloads
    pwd

When we run the list target, both pwd commands will display the path of the Makefile's directory. The second pwd will not show the path of ~/Downloads because each command in a Makefile runs in a separate shell instance.

Solution

To ensure that the second pwd displays the path of ~/Downloads, we need to bind the commands together. Here’s how to do it:

list:
    pwd
    cd ~/Downloads; pwd

If we want to run multiple commands after changing to a new directory, we can append the commands using && to ensure they execute in the same shell instance:

list:
    @pwd
    @(cd ~/Downloads && \
    pwd && \
    ls)

In this example, the @ sign before the command prevents the command itself from being displayed when running the task. The && ensures that all commands run sequentially in the same shell instance.

By using this approach, you can run multiple commands in a subdirectory within your Makefile efficiently.