如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
我在.bashrc中定义了一个函数,这使得这更容易。
command_exists () {
type "$1" &> /dev/null ;
}
下面是一个如何使用它的示例(来自我的.bash_profile)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
其他回答
如果你的男人/女孩不能在这里得到答案中的东西,并且你的头发从你的背部,尝试使用bash-c运行相同的命令。看看这个梦游性谵妄。这是运行$(子命令)时真正发生的情况:
第一它可以给你完全不同的输出。
$ command -v ls
alias ls='ls --color=auto'
$ bash -c "command -v ls"
/bin/ls
第二它根本不会给你任何输出。
$ command -v nvm
nvm
$ bash -c "command -v nvm"
$ bash -c "nvm --help"
bash: nvm: command not found
如果您可以:
which programname
...
type -P programname
which命令可能有用。男子谁
如果找到可执行文件,则返回0;如果找不到或不可执行,则返回1:
NAME
which - locate a command
SYNOPSIS
which [-a] filename ...
DESCRIPTION
which returns the pathnames of the files which would
be executed in the current environment, had its
arguments been given as commands in a strictly
POSIX-conformant shell. It does this by searching
the PATH for executable files matching the names
of the arguments.
OPTIONS
-a print all matching pathnames of each argument
EXIT STATUS
0 if all specified commands are
found and executable
1 if one or more specified commands is nonexistent
or not executable
2 if an invalid option is specified
这样做的好处是,它可以确定可执行文件在运行环境中是否可用-这节省了一些问题。。。
我在.bashrc中定义了一个函数,这使得这更容易。
command_exists () {
type "$1" &> /dev/null ;
}
下面是一个如何使用它的示例(来自我的.bash_profile)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
我使用这个,因为它非常简单:
if [ $(LANG=C type example 2>/dev/null | wc -l) = 1 ]; then
echo exists;
else
echo "not exists";
fi
or
if [ $(LANG=C type example 2>/dev/null | wc -l) = 1 ]; then
echo exists
else
echo "not exists"
fi
它使用shell内置程序和程序的回声状态进行标准输出,而不使用标准错误。另一方面,如果找不到命令,它只会将状态返回到标准错误。