Last active
January 9, 2024 08:52
-
-
Save nezort11/a185b2206354a846001d58f649f8c1d7 to your computer and use it in GitHub Desktop.
Bash script to execute script from package.json without package manager (npm run, yarn, pnpm) or node_modules installed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
PACKAGE_FILE="package.json" | |
PACKAGE_RUN_COMMAND="npm" | |
RUN_COMMAND="bash ${0}" | |
SCRIPT="$1" | |
# Check package manager | |
if [ -f "package-lock.json" ]; then | |
PACKAGE_RUN_COMMAND="npm" | |
fi | |
if [ -f "yarn.lock" ]; then | |
PACKAGE_RUN_COMMAND="yarn" | |
fi | |
if [ -f "pnpm-lock.yaml" ]; then | |
PACKAGE_RUN_COMMAND="pnpm" | |
fi | |
# Check run as superuser | |
if [ "$EUID" -eq 0 ]; then | |
RUN_COMMAND="sudo $RUN_COMMAND" | |
fi | |
# Check package file | |
if [ -f "$PACKAGE_FILE" ]; then | |
# Extract the script command using jq (Install jq: https://stedolan.github.io/jq/download/) | |
script_command=$(jq -r ".scripts.\"$SCRIPT\"" "$PACKAGE_FILE") | |
if [ ! -z "$script_command" ] && [ "$script_command" != "null" ]; then | |
eval "$(echo $script_command | sed -e "s/${PACKAGE_RUN_COMMAND}/${RUN_COMMAND}/g") ${@:2}" | |
else | |
echo "Script '$SCRIPT' not found in $PACKAGE_FILE" | |
fi | |
else | |
echo "$PACKAGE_FILE not found" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
./run.sh scriptname
orbash run.sh scriptname