Reputation: 62384
My objective is to only install this npm package if it's not already available. 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?
Upvotes: 7
Views: 8395
Reputation: 91
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
Upvotes: 1
Reputation: 7348
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
Upvotes: 19
Reputation: 1836
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 packagesgrep -c $package
prints a count of lines containing $package (which is substituted to 'widdershins' in our case)-eq
is an equals check, e.g. $a -eq $b
returns true if $a is equal to $b, and false otherwise.-d
checks if the given argument is a directory (returns true if it is)!
is the negation operator, in our case is negates the -d result-o
is the logical or operatorTo sum it up:
This could also help you.
Upvotes: 12