How to check if npm script exists?

EDIT: As mentioned by Marie and James if you only want to run the command if it exists, npm has an option for that:

npm run test --if-present

This way you can have a generic script that work with multiple projects (that may or may not have an specific task) without having the risk of receiving an error.



You could do a grep to check for the word test:

npm run | grep -q test

this return true if the result in npm run contains the word test

In your script it would look like this:


ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"

while read MYAPP; do # reads from a list of projects
  cd "$FOLDER"
  if npm run | grep -q test; then
    npm run test
    echo ""
done < "${ROOT_PATH}/../assets/apps-manifest"

It just would be a problem if the word test is in there with another meaning Hope it helps

The right solution is using the if-present flag:

npm run test --if-present