为了账号安全,请及时绑定邮箱和手机立即绑定

请教下在编写bash时,如果要判断某条命令是否存在,应该如何写呢?

请教下在编写bash时,如果要判断某条命令是否存在,应该如何写呢?

qq_遁去的一_1 2023-04-18 18:14:57
我尝试了如下的写法,不知道错误在哪里if [ -n `which brew`]; then  echo 'brew exist'else  echo 'brew does not exist'fi用来判断brew命令是否存在,可是明明没有brew,却总是显示 "brew exist"
查看完整描述

3 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

最好避免使用 which,做为一个外部的工具,并不一定存在,在发行版之间也会有区别,有的系统的 which 命令不会设置有效的 exit status,存在一定的不确定性。

Bash 有提供一些内建命令如 hash、type、command 也能达到要求。

$ 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; }


查看完整回答
反对 回复 2023-04-21
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

which want_to_find > /dev/null 2>&1if [ $? == 0 ]; then
    echo "exist"else
    echo "dose not exist"fi


查看完整回答
反对 回复 2023-04-21
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

if hash brew 2>/dev/null; then
echo 'brew exist'
else
echo 'brew does not exist'
fi

Hash是一个缓存表
系统初始Hash表是空的,如果系统重启也会清空,当外部命令执行是会到PATH里找该命令,然后记录在Hash里,当再执行时就到Hash里取,这样会加快执行速度。


查看完整回答
反对 回复 2023-04-21
  • 3 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信