Check if a program exists in bash

I am trying to check if md5sum or digest exists on solaris and script is used on different machines.

Here is the function in sh script which is called from a ksh script

getMD5cmd ()
{
    PATH="${PATH}:/bin:/usr/bin:/usr/sfw/bin:/usr/local/bin:/usr/sbin/bin"
    if type -p md5sum;then
        MD5CMD=`type -p md5sum`
    elif type -p digest;then
        MD5CMD="`type -p digest` -a md5"
    fi
    echo "HERE ${MD5CMD}"
}

When I run scripts I get

-p not found
md5sum not found
-p not found
digest is /bin/digest
HERE

However, when I type it in a terminal, works as exptected

Any Ideas? Thanks



当你设置PATH时,知道命令在哪里似乎是不必要的。

getMD5cmd ()
{
    PATH=${PATH}:/bin:/usr/bin:/usr/sfw/bin:/usr/local/bin:/usr/sbin/bin
    md5sum /dev/null >/dev/null 2>&1 && MD5CMD=md5sum || MD5CMD="digest -a md5"
    echo "HERE ${MD5CMD}"
}
getMD5cmd

Have you tried the following syntax:

MD5CMD="$(type -p md5sum digest |sed -e 's/digest$/digest -a md5/' |head -1)"
if [ -z "$MD5CMD" ]; then
    echo 'no md5 sum command found' >&2
    exit 1
fi
echo "HERE $MD5CMD"

I tried this in Cygwin and type will return multiple rows, so it works.

链接地址: http://www.djcxy.com/p/9790.html

上一篇: 用于这种bash文件名提取技术?

下一篇: 检查一个程序是否存在于bash中