如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
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
这样做的好处是,它可以确定可执行文件在运行环境中是否可用-这节省了一些问题。。。
其他回答
如果您检查程序是否存在,您可能会稍后运行它。为什么不先尝试运行它?
if foo --version >/dev/null 2>&1; then
echo Found
else
echo Not found
fi
这是一个更值得信赖的检查程序运行,而不仅仅是查看PATH目录和文件权限。
此外,您可以从程序中获得一些有用的结果,例如其版本。
当然,缺点是有些程序启动起来会很重,有些程序没有--version选项可以立即(并成功)退出。
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
这样做的好处是,它可以确定可执行文件在运行环境中是否可用-这节省了一些问题。。。
如果没有任何可用的外部类型命令(在这里是理所当然的),我们可以使用符合POSIX的env-i sh-c“type cmd 1>/dev/null 2>&1”:
# Portable version of Bash's type -P cmd (without output on stdout)
typep() {
command -p env -i PATH="$PATH" sh -c '
export LC_ALL=C LANG=C
cmd="$1"
cmd="`type "$cmd" 2>/dev/null || { echo "error: command $cmd not found; exiting ..." 1>&2; exit 1; }`"
[ $? != 0 ] && exit 1
case "$cmd" in
*\ /*) exit 0;;
*) printf "%s\n" "error: $cmd" 1>&2; exit 1;;
esac
' _ "$1" || exit 1
}
# Get your standard $PATH value
#PATH="$(command -p getconf PATH)"
typep ls
typep builtin
typep ls-temp
至少在Mac OS X v10.6.8(雪豹)上,使用Bash 4.2.24(2)命令-vls与移动的/bin/ls温度不匹配。
剧本
#!/bin/bash
# Commands found in the hash table are checked for existence before being
# executed and non-existence forces a normal PATH search.
shopt -s checkhash
function exists() {
local mycomm=$1; shift || return 1
hash $mycomm 2>/dev/null || \
printf "\xe2\x9c\x98 [ABRT]: $mycomm: command does not exist\n"; return 1;
}
readonly -f exists
exists notacmd
exists bash
hash
bash -c 'printf "Fin.\n"'
后果
✘ [ABRT]: notacmd: command does not exist
hits command
0 /usr/bin/bash
Fin.
我从来没有得到以前的答案来处理我可以访问的盒子。首先,类型已经安装(做更多的事情)。因此需要内置指令。此命令适用于我:
if [ `builtin type -p vim` ]; then echo "TRUE"; else echo "FALSE"; fi