How to run a bash script with NPM

April 06, 2020

npm

TLDR

Simply point to the bash script with a ./ at the front of the file path:

bash
1."scripts": {
2. "npmScriptName": "./bashScript.sh"
3.}

Example for running a bash script with NPM

Make a simple bash script and include #!/usr/bin/env bash at the top:

bash
1.#!/usr/bin/env bash
2.printf 'test'

Then just provide a path to the file itself with a ./:

bash
1."scripts": {
2. "yup": "./test.sh"
3.}

Then run the script:

bash
1.npm run yup

It should output "test" in the terminal:

bash
1.❯ npm run yup
2.
3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood
4.> ./test.sh
5.
6.test

Problems

Check your permissions

If you do not have permissions to run the file you'll get an error

bash
1.sh: ./test.sh: Permission denied
2.npm ERR! code ELIFECYCLE
3.npm ERR! errno 126

You can grant permissions by running chmod +x on unix.

bash
1.chmod +x ./test.sh

Then running the commmand will work

bash
1.❯ npm run yup
2.
3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood
4.> ./test.sh
5.
6.test

Forgot ./

If you don't put . before the /, like /test.sh, then you will get the following error:

bash
1.❯ npm run yup
2.
3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood
4.> /test.sh
5.
6.sh: /test.sh: No such file or directory
7.npm ERR! code ELIFECYCLE
8.npm ERR! syscall spawn

Because it's looking for a directory instead of an executable. If you don't have either . or / then it will think test.sh is a command:

bash
1.❯ npm run yup
2.
3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood
4.> test.sh
5.
6.sh: test.sh: command not found
7.npm ERR! code ELIFECYCLE
8.npm ERR! syscall spawn
9.npm ERR! file sh
10.npm ERR! errno ENOENT