linux - Shell(Bash)中如何判断是否存在某个命令
怪我咯
怪我咯 2017-04-17 11:09:26
0
3
710

在编写bash时,如果要判断某条命令是否存在,应该如何写呢?
我尝试了如下的写法,不知道错误在哪里

if [ -n `which brew`]; then
 echo 'brew exist'
else
 echo 'brew does not exist'
fi

用来判断brew命令是否存在,可是明明没有brew,却总是显示 "brew exist"

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
Ty80

It is best to avoid using which. As an external tool, it does not necessarily exist. There will be differences between releases. The which command of some systems will not set a valid exit status, and there is some uncertainty. sex.

Bash provides some built-in commands such as hash, type, and command that can also meet the requirements.

$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }

See http://stackoverflow.com/questions/59...

for details
洪涛
which want_to_find > /dev/null 2>&1
if [ $? == 0 ]; then
    echo "exist"
else
    echo "dose not exist"
fi
巴扎黑
if which brew 2>/dev/null; then
  echo "brew exists!"
else
  echo "nope, no brew installed."
fi

which When the command cannot be found, "xxx not found" will be output to stderr.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template