一个在bash和zsh中都有效的函数:
# Return the first pathname in $PATH for name in $1 function cmd_path () { if [[ $ZSH_VERSION ]]; then whence -cp "$1" 2> /dev/null else # bash type -P "$1" # No output if not in $PATH fi }
如果未找到该命令,则返回非零 $PATH 。
$PATH
检查Bash脚本中是否存在程序 很好地涵盖了这一点。在任何shell脚本中,您最好不要运行 command -v $command_name 用于测试是否 $command_name 可以运行。在bash中你可以使用 hash $command_name ,也可以散列任何路径查找的结果,或者 type -P $binary_name 如果你只想看二进制文件(不是函数等)
command -v $command_name
$command_name
hash $command_name
type -P $binary_name
which <cmd>
也看到了 选项 which 支持 对于别名,如果适用于您的情况。
which
例
$ which foobar which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG $ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi foobar is NOT found in PATH, of course it does not mean it is not installed. $
PS:请注意,并非安装的所有内容都可能在PATH中。通常,为了检查某些东西是否“已安装”,可以使用与OS相关的安装相关命令。例如。 rpm -qa | grep -i "foobar" 对于RHEL。
rpm -qa | grep -i "foobar"
我在安装脚本中具有的功能就是这样做的
function assertInstalled() { for var in "$@"; do if ! which $var &> /dev/null; then echo "Install $var!" exit 1 fi done }
示例电话:
assertInstalled zsh vim wget python pip git cmake fc-cache
有五种方式,4种用于bash,1种用于zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
你可以把它们中的任何一个放到你的 if 条款。根据我的测试( https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/ ),在bash中推荐第一种和第三种方法,在速度方面建议在zsh中使用第五种方法。
if