Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在if条件中检查系统上是否存在两个特定程序?_Bash - Fatal编程技术网

Bash 如何在if条件中检查系统上是否存在两个特定程序?

Bash 如何在if条件中检查系统上是否存在两个特定程序?,bash,Bash,我的.bashrc中有以下内容可用于打印外观有趣的消息: fortune | cowsay -W 65 如果计算机没有安装fortune或cowsay,我不想让这行运行 执行此检查的最佳或最简单的方法是什么?如果您不想在未安装的情况下看到错误消息,您可以这样做: (fortune | cowsay -W 65) 2>/dev/null 您可以使用type或which或hash来测试命令是否存在 在所有这些代码中,只对可执行文件起作用,我们将跳过它 试着做点什么 if type fort

我的.bashrc中有以下内容可用于打印外观有趣的消息:

fortune | cowsay -W 65
如果计算机没有安装
fortune
cowsay
,我不想让这行运行


执行此检查的最佳或最简单的方法是什么?

如果您不想在未安装的情况下看到错误消息,您可以这样做:

(fortune | cowsay -W 65) 2>/dev/null

您可以使用
type
which
hash
来测试命令是否存在

在所有这些代码中,
只对可执行文件起作用,我们将跳过它

试着做点什么

if type fortune &> /dev/null; then
    if type cowsay &> /dev/null; then
        fortune | cowsay -W 65
    fi
fi
或者,不带
的情况下,如果
s:

type fortune &> /dev/null && type cowsay &> /dev/null && (fortune | cowsay -W 65)

type
是实现此目的的工具。这是一个Bash内置。它并不像我曾经想的那样过时,那就是
排版
。您可以使用一个命令检查这两个选项

if type fortune cowsay
then
  fortune | cowsay -W 65
fi
此外,它还会在STDOUT和STDERR之间分割输出,因此您可以抑制成功消息

type fortune cowsay >/dev/null
# or failure messages
type fortune cowsay 2>/dev/null
# or both
type fortune cowsay &>/dev/null