简体   繁体   English

如何判断bash中是否安装了npm模块

[英]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是否定运算符,在我们的例子中是否定 -d 结果
  • -o is the logical or operator -o是逻辑或运算符

To sum it up:把它们加起来:

  • First code: if the $package is installed, then the -eq result is false and this causes the if statement to be false.第一个代码:如果 $package 已安装,则 -eq 结果为假,这将导致 if 语句为假。 If $package is not installed, then the -eq result is true (and the if statement is also true).如果未安装 $package,则 -eq 结果为真(if 语句也为真)。
  • Second code: in addition to description of first code, if node_module is a directory, then the if statement is false.第二段代码:除了第一段代码的描述外,如果node_module是一个目录,则if语句为假。 If node_module is not a directory then the if statement is true.如果 node_module 不是目录,则 if 语句为真。 And this is independend from the -eq result because of the logical or connection.由于逻辑或连接,这与 -eq 结果无关。

This could also help you. 也可以帮助你。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM