I am testing whether command exist like this:
if hash pm2 2>/dev/null; then
echo "already exist"
else
npm install --global pm2
fi
but in fact I just want to do this
if not exist
install it
fi
I tried this
if [ ! hash pm2 2>/dev/null ]; then
npm install --global pm2
fi
it is not ok
Just negate the condition in your if
:
if ! hash pm2 2>/dev/null; then
# ^
npm install --global pm2
fi
If you want to use the test command [
you have to enclose the command within a $()
to get it evaluated:
if [ ! $(hash pm2 2>/dev/null) ]; then
Example
Let's create an empty file:
$ touch a
And check if it does not contain some text, eg, 5:
$ if ! grep -sq 5 a; then echo "no 5 here"; fi
no 5 here
$ if [ ! $(grep -sq 5 a) ]; then echo "no 5 here"; fi
no 5 here