views:

138

answers:

4

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

A: 

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.

amphetamachine
this only works in bash
rojanu
A: 
if which md5sum >/dev/null 2>&1; then
    md5cmd="md5sum"
elif  which digest >/dev/null 2>&1; then
    md5cmd="digest -a md5"
else
    echo "No md5 command found" >&2
    exit 1
fi

$md5cmd YOUR_FILE
Jürgen Hötzel
first condition evaluates to true even tough there is no md5sum on the machine
rojanu
I think the reason for that is "which" always have an output on Solaris, when command is not found the response is "no md5sum in /usr/bin /vol2/bin"
rojanu
+1  A: 

You are likely running ksh or possibly Bash for your interactive shell. Both of these have a -p option for type. The shell (probably sh) that your script is running in has type but doesn't have the -p option so it's looking for "-p" as the name of an executable and it doesn't find it.

So you could change your script to use ksh or you could use the which program. The latter is probably more portable, since some systems don't have ksh.

Dennis Williamson
I can't believe how naive I could get, never even spared a thought for that.Thanks for shedding some light on that. I converted script to bash for now and my code works
rojanu
oh well, I converted my script to be bash and ended up using your suggestion
rojanu
A: 

As you are setting the PATH, knowing where precisely the command is seems unnecessary.

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
jlliagre
I am not interested in exact path. This script sits on the users home/bin and depending on the machine the user logs on, I wan't to know which of the commands exists on the system.
rojanu