[英]How to determine if npm module installed in bash
My objective is to only install this npm package if it's not already available.我的目标是仅在 npm package 不可用的情况下安装它。 This continues to to execute even when I've installed the module globally.
即使我已经全局安装了模块,这也会继续执行。
if [ npm list -g widdershins &> /dev/null ] || [ ! -d node_modules ]; then
npm install widdershins --no-shrinkwrap
fi
How can I adjust this to detect when it's installed globally?如何调整它以检测它何时安装在全局范围内?
if you want a one liner:如果你想要一个班轮:
Local当地的
npm list | grep widdershins || npm install widdershins --no-shrinkwrap
Global:全球的:
npm list -g | grep widdershins || npm install -g widdershins --no-shrinkwrap
package='widdershins'
if [ `npm list -g | grep -c $package` -eq 0 ]; then
npm install $package --no-shrinkwrap
fi
alternative including the directory check:替代方法包括目录检查:
package='widdershins'
if [ `npm list -g | grep -c $package` -eq 0 -o ! -d node_module ]; then
npm install $package --no-shrinkwrap
fi
Explaination:解释:
npm list -g
lists all installed packages npm list -g
列出所有已安装的包grep -c $package
prints a count of lines containing $package (which is substituted to 'widdershins' in our case) grep -c $package
打印包含 $package 的行数(在我们的例子中替换为 'widdershins')-eq
is an equals check, eg $a -eq $b
returns true if $a is equal to $b, and false otherwise. -eq
是一个相等检查,例如,如果 $a 等于 $b,则$a -eq $b
返回 true,否则返回 false。-d
checks if the given argument is a directory (returns true if it is) -d
检查给定参数是否为目录(如果是则返回真)!
is the negation operator, in our case is negates the -d result-o
is the logical or operator -o
是逻辑或运算符To sum it up:把它们加起来:
This worked for me:这对我有用:
package_name='widdershins'
if [[ "$(npm list -g $package_name)" =~ "empty" ]]; then
echo "Installing $package_name ..."
npm install -g $package_name
else
echo "$package_name is already installed"
fi
npm list -g package-name
returns empty when is not installed, so with that condition you can check if it contains the string empty npm list -g package-name
未安装时返回空,因此您可以检查它是否包含字符串空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.