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.

Source: https://docs.npmjs.com/cli/run-script

EDIT

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:

#!/bin/bash

ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
BASE_PATH="${ROOT_PATH}/../.."

while read MYAPP; do # reads from a list of projects
  PROJECT="${MYAPP}"
  FOLDER="${BASE_PATH}/${PROJECT}"
  cd "$FOLDER"
  if npm run | grep -q test; then
    npm run test
    echo ""
  fi
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