Bash, ... 检查程序是否安装,使用 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29749205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:50:25  来源:igfitidea点击:

Bash, ... check if a program is installed or not, using bash script

bash

提问by sensorario

I am trying to create a little script that check if a program is installed or not. I am trying with tmux, ...

我正在尝试创建一个小脚本来检查是否安装了程序。我正在尝试使用 tmux,...

`tmux --help` | grep "tmux: command not found" &> /dev/null
if [ $? == 1 ]; then
    echo "tmux is not installed"
    exit
fi

After installation of tmux, I get:

安装 tmux 后,我得到:

usage: tmux [-2lquvV] [-c shell-command] [-f file] [-L socket-name]
            [-S socket-path] [command [flags]]
tmux is not installed

If a program is not installed, appair the string "tmux: command not found". This could explain why I grep output of tmux --helpcommand. Is a correct way to check if tmux is installed or not?

如果未安装程序,则显示字符串“tmux: command not found”。这可以解释为什么我 greptmux --help命令的输出。检查是否安装了 tmux 的正确方法是什么?

The script alwais echoes "tmux is not installed". Even if I install tmux. What's wrong with it?

脚本总是回应“tmux 未安装”。即使我安装了 tmux。它出什么问题了?

回答by Etan Reisner

You can use the command, typeand hashbuilt-in functions to test whether a given command is usable in the current shell session.

您可以使用command,typehash内置函数来测试给定命令在当前 shell 会话中是否可用。

This will not tell you if it is available in some location not in the current PATHhowever.

这不会告诉您它是否在当前不在的某个位置可用PATH

You should avoid using whichfor this purpose (even though that is the default suggestion you will get from many people) because it isn't a standardized tool (not completely) and it is an externaltool as compared to the above which are all built-in to the shell (and is thus more expensive of a check).

您应该避免which为此目的使用(即使这是您从许多人那里得到的默认建议),因为它不是标准化工具(不完全),并且与上述所有内置工具相比,它是一个外部工具 -进入外壳(因此检查成本更高)。