how to get Logical Not in shell?

梦想的初衷 提交于 2019-12-11 14:38:58

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/36859170/how-to-get-logical-not-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!