Last active
February 5, 2026 20:43
-
-
Save s-h-a-d-o-w/d1be4eb4ecad3576af8fa69c248be615 to your computer and use it in GitHub Desktop.
Batch script - "smart" package manager command for JS projects
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 sh | |
| find_package_manager() { | |
| dir="$PWD" | |
| found_pm="" | |
| while true; do | |
| pm="" | |
| # Check package.json for packageManager field | |
| if [ -f "$dir/package.json" ]; then | |
| pkg_mgr=$(jq -r '.packageManager // empty' "$dir/package.json" 2>/dev/null | cut -d'@' -f1) | |
| if [ -n "$pkg_mgr" ]; then | |
| pm="$pkg_mgr" | |
| fi | |
| fi | |
| # Check for lockfiles if packageManager not found in package.json | |
| if [ -z "$pm" ]; then | |
| if [ -f "$dir/package-lock.json" ]; then | |
| pm="npm" | |
| elif [ -f "$dir/yarn.lock" ]; then | |
| pm="yarn" | |
| elif [ -f "$dir/pnpm-lock.yaml" ]; then | |
| pm="pnpm" | |
| elif [ -f "$dir/bun.lock" ]; then | |
| pm="bun" | |
| elif [ -f "$dir/bun.lockb" ]; then | |
| pm="bun" | |
| fi | |
| fi | |
| # Return the package manager found closest to execution directory | |
| if [ -n "$pm" ]; then | |
| echo $pm | |
| return 0 | |
| fi | |
| # Move to parent directory | |
| parent=$(dirname "$dir") | |
| if [ "$parent" = "$dir" ] || [ "$parent" = "/" -a "$dir" = "/" ]; then | |
| break | |
| fi | |
| dir="$parent" | |
| done | |
| echo "No recognized package manager or lockfile found in hierarchy." >&2 | |
| return 1 | |
| } | |
| # Find and execute the package manager | |
| pm=$(find_package_manager) | |
| if [ $? -eq 0 ]; then | |
| exec cmd.exe /c "$pm $*" | |
| else | |
| exit 1 | |
| fi |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On Windows, run like this with WSL:
@echo off wsl pm.sh %*