我正在测试命令是否存在这样:
if hash pm2 2>/dev/null; then
echo "already exist"
else
npm install --global pm2
fi
但实际上我只是想这样做
if not exist
install it
fi
我试过这个
if [ ! hash pm2 2>/dev/null ]; then
npm install --global pm2
fi
不行
答案 0 :(得分:2)
只是否定if
中的条件:
if ! hash pm2 2>/dev/null; then
# ^
npm install --global pm2
fi
如果要使用测试命令[
,则必须将命令括在$()
内以进行评估:
if [ ! $(hash pm2 2>/dev/null) ]; then
让我们创建一个空文件:
$ touch a
并检查它是否包含某些文字,例如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