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 bash2.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 yup2.3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood4.> ./test.sh5.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 denied2.npm ERR! code ELIFECYCLE3.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 yup2.3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood4.> ./test.sh5.6.test
Forgot ./
If you don't put .
before the /
, like /test.sh
, then you will get the following error:
bash
1.❯ npm run yup2.3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood4.> /test.sh5.6.sh: /test.sh: No such file or directory7.npm ERR! code ELIFECYCLE8.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 yup2.3.> Codinhood@0.1.0 yup /Users/cody/projects/codinhood4.> test.sh5.6.sh: test.sh: command not found7.npm ERR! code ELIFECYCLE8.npm ERR! syscall spawn9.npm ERR! file sh10.npm ERR! errno ENOENT