Change directory in Makefile
TODO: collapasable, copyable, download, etc
In a Makefile, is this good enough to cd into a directory and back out? init-app-data: @echo "Initializing app data..." cd app-ui @$(NPX_BUILD_TOOL) prisma db push cd ..
The code snippet you provided for a Makefile target attempts to change directories to app-ui
, runs a command with $(NPX_BUILD_TOOL) prisma db push
, and then attempts to change back to the original directory. However, this will not work as expected because each line in a Makefile recipe is executed in a separate subshell by default. This means that the cd
to app-ui
only affects the subshell for that specific line, and the directory change does not persist to the next line.
To correctly handle changing directories within a Makefile recipe, you can group the commands that should be executed in the same directory into a single shell command using &&
to chain them, or use a subshell. Here are two ways to do this:
Using command chaining with
&&
:init-app-data: @echo "Initializing app data..." cd app-ui && $(NPX_BUILD_TOOL) prisma db push
Here,
cd app-ui
changes the directory, and$(NPX_BUILD_TOOL) prisma db push
is only executed if the directory change was successful.Using a subshell:
init-app-data: @echo "Initializing app data..." @(cd app-ui && $(NPX_BUILD_TOOL) prisma db push)
This encapsulates the
cd
and the command into a single subshell. The directory change and the command execution both happen in the subshell, so they are effectively in the same directory context.
Both methods ensure that the directory change affects the command execution and that you don't need to change back to the original directory, as each command's effects on the directory are scoped to their execution shell.
Change directory in Makefile created at Tue Jan 20 1970 20:23:33 GMT+0000 (Coordinated Universal Time)Related Chats
Change directory in Makefile 0.998
Monitor Specific Directories 0.326
Nohup com env em shell 0.303
Prisma HMR Disconnect Solution 0.292
Update Docker Compose Envvars 0.289
GitHub Actions: Deploy on Change 0.284
Config Environment Variables Override 0.273
Prisma Setup and Usage 0.269
New chat 0.268
New chat 0.260