Skip to content

Instantly share code, notes, and snippets.

@npretto
Created January 12, 2026 10:41
Show Gist options
  • Select an option

  • Save npretto/2412fb1b4459d6c4a7d14b3b31ac6112 to your computer and use it in GitHub Desktop.

Select an option

Save npretto/2412fb1b4459d6c4a7d14b3b31ac6112 to your computer and use it in GitHub Desktop.
automatically detect yarn/bun/npm
# find package manager by looking for lockfiles in current and parent directories
function find-pkg-manager() {
local dir="$PWD"
while [ "$dir" != "/" ]; do
if [ -f "$dir/bun.lockb" ]; then
echo "bun|$dir/bun.lockb"
return 0
elif [ -f "$dir/pnpm-lock.yaml" ]; then
echo "pnpm|$dir/pnpm-lock.yaml"
return 0
elif [ -f "$dir/yarn.lock" ]; then
echo "yarn|$dir/yarn.lock"
return 0
elif [ -f "$dir/package-lock.json" ]; then
echo "npm|$dir/package-lock.json"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
# detect yarn/npm/pnpm/bun and install deps
function i() {
local result=$(find-pkg-manager)
if [ $? -eq 0 ]; then
local pm=$(echo "$result" | cut -d'|' -f1)
local lockfile=$(echo "$result" | cut -d'|' -f2)
echo "detected $lockfile, running $pm ${@:-install}"
$pm "${@:-install}"
else
echo "No lockfile found in current or parent directories"
fi
}
# detect package manager and run command
function r(){
local result=$(find-pkg-manager)
if [ $? -eq 0 ]; then
local pm=$(echo "$result" | cut -d'|' -f1)
local lockfile=$(echo "$result" | cut -d'|' -f2)
echo "detected $lockfile, running $pm run $@"
$pm run "$@"
else
echo "No lockfile found in current or parent directories"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment