sajad torkamani

Suppose you’re working on a WordPress project and you have your package.json file in your theme directory like this:

wp-content/themes/my-custom-theme/package.json

Instead of changing to that directory to run a command like npm run dev, you want a bin/dev command at the root of your project. When you run this bin/dev command but then exit the foreground process via Ctrl + C or similar, you want to stay in the root of the project.

For that use case, you want to create a bin/dev script that looks like this:

#!/usr/bin/env bash

set -euo pipefail

(cd wp-content/themes/my-custom-theme && npm install && npm run dev)

Notice the commands in the last line are surrounded by brackets – (...). That makes your commands run in a sub-shell so that when you exit that command, the sub-shell is closed and you return to the directory you were on when you first invoked the bin/dev script.