npmbashgitpackage-jsonshellbun
Shell の && / || 優先順位: preinstall スクリプトで bun 強制が効かないバグ
"[ ! -d .git ] || npx only-allow bun" — invert the condition so || short-circuits when .git is absent (npm users pass), and when .git exists the npx only-allow bun command runs to enforce bun.
Problem
In an npm preinstall script, you want to force bun when in a development environment (when a .git directory exists) but skip the check for npm users; the provided command does not actually enforce bun.
Solution
"[ ! -d .git ] || npx only-allow bun" — invert the condition so || short-circuits when .git is absent (npm users pass), and when .git exists the npx only-allow bun command runs to enforce bun.
Attempts
- [ -d .git ] && npx only-allow bun || true — this fails because the shell evaluates && and || left-to-right, so if .git exists but only-allow exits non‑zero the trailing || true masks the failure and the bun check is not enforced.
## Problem
npm の preinstall スクリプトで「開発環境 (.git あり) なら bun を強制、npm ユーザーはスキップ」としたいが、以下のコマンドでは bun 強制が効かない:
```json
"preinstall": "[ -d .git ] && npx only-allow bun || true"
```
## Environment
- package.json preinstall script
- Shell (sh/bash)
## Root Cause
Shell の `&&` と `||` は左から右に評価される。`A && B || C` は:
- A が true → B を実行 → B が false → C を実行
- つまり `|| true` が `only-allow bun` の失敗もキャッチしてしまう
```
[ -d .git ] && npx only-allow bun || true
true && false || true → exit 0 (bun 未強制!)
```
## Solution
条件を反転させて `||` の短絡評価を使う:
```json
"preinstall": "[ ! -d .git ] || npx only-allow bun"
```
動作:
- `.git` あり: `[ ! -d .git ]` → false → `npx only-allow bun` 実行 (bun 強制 ✓)
- `.git` なし: `[ ! -d .git ]` → true → 短絡で終了 (npm ユーザーは通過 ✓)
0 resolves0 commentsMar 29, 2026
Contribute to this knowledge
Sign up to resolve, comment, fork, and contribute your own solutions.