如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
这取决于您是否想知道它是否存在于$PATH变量中的某个目录中,或者您是否知道它的绝对位置
if which programname >/dev/null; then
echo exists
else
echo does not exist
fi
否则使用
if [ -x /path/to/programname ]; then
echo exists
else
echo does not exist
fi
在第一个示例中,重定向到/dev/null/会抑制哪个程序的输出。
其他回答
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
这样做的好处是,它可以确定可执行文件在运行环境中是否可用-这节省了一些问题。。。
迟到的回答,但这就是我最后做的。
我只是检查我执行的命令是否返回错误代码。如果返回0,则表示程序已安装。此外,您还可以使用它检查脚本的输出。以这个脚本为例。
foo.sh
#!/bin/bash
echo "hello world"
exit 1 # throw some error code
示例:
# outputs something bad... and exits
bash foo.sh $? -eq 0 || echo "something bad happened. not installed" ; exit 1
# does NOT outputs nothing nor exits because dotnet is installed on my machine
dotnet --version $? -eq 0 || echo "something bad happened. not installed" ; exit 1
基本上,所有这些都是检查命令运行的退出代码。即使命令退出代码不是0,这个问题上最被接受的答案也将返回true。
#!/bin/bash
a=${apt-cache show program}
if [[ $a == 0 ]]
then
echo "the program doesn't exist"
else
echo "the program exists"
fi
#程序不是字面意思,您可以将其更改为要检查的程序名称
我想说,由于悬挂别名,没有任何可移植和100%可靠的方法。例如:
alias john='ls --color'
alias paul='george -F'
alias george='ls -h'
alias ringo=/
当然,只有最后一个是有问题的(林戈没有冒犯!)。但从command-v的角度来看,它们都是有效的别名。
为了拒绝像ringo这样的悬空命令,我们必须解析shell内置别名命令的输出并递归到它们中(这里命令-v并不优于别名)。没有任何可移植的解决方案,即使是特定于Bash的解决方案也相当乏味。
注意,类似这样的解决方案将无条件拒绝别名ls='ls-F':
test() { command -v $1 | grep -qv alias }
仅zsh,但对于zsh脚本非常有用(例如,在编写完成脚本时):
zsh/parameter模块可以访问内部命令哈希表等。来自man zshmodules:
THE ZSH/PARAMETER MODULE
The zsh/parameter module gives access to some of the internal hash ta‐
bles used by the shell by defining some special parameters.
[...]
commands
This array gives access to the command hash table. The keys are
the names of external commands, the values are the pathnames of
the files that would be executed when the command would be in‐
voked. Setting a key in this array defines a new entry in this
table in the same way as with the hash builtin. Unsetting a key
as in `unset "commands[foo]"' removes the entry for the given
key from the command hash table.
尽管它是一个可加载的模块,但只要zsh不与--simulate一起使用,它似乎是默认加载的。
例子:
martin@martin ~ % echo $commands[zsh]
/usr/bin/zsh
要快速检查某个命令是否可用,只需检查哈希中是否存在密钥:
if (( ${+commands[zsh]} ))
then
echo "zsh is available"
fi
请注意,散列将包含$PATH文件夹中的任何文件,无论它们是否可执行。为了绝对确定,您必须对此进行统计:
if (( ${+commands[zsh]} )) && [[ -x $commands[zsh] ]]
then
echo "zsh is available"
fi