Reputation: 61
First time poster, here, so go easy on me. :)
Pretty sure nobody's yet asked this in researching this question.
Short version: How can I tell a shell script to use one command versus the other, depending on which box I run the shell script on? Example: on Box 1, I want to run md5 file.txt
. On Box 3, I want to run md5sum file.txt
. I'm thining it's an IF command where if the output of md5
is a failure, use md5sum
instead. Just don't know how to check and see whether the output of md5
is a failure or not
Long version: I have 3 boxes that I work with. Box 1 and 3 are the receivers of a file from Box 2, and they receive the file when I invoke a script on box 1/3 as follows: ftpget.sh file.txt
I have a shell script that does an FTP GET and grabs a file from Box 2. It then does an md5 on the source file from Box 2 and the destination file, which'll be on Box 1 or 3, depending on which one I executed the script from. The hashes must match, of course.
The problem is this: The code is written to use md5
, and while Box 1 uses md5, Box 3 uses md5sum
. So when I execute the script from Box 1, it works great. When I execute the script from Box 3, it fails because Box 3 uses md5sum, not md5.
So I was thinking: what's the best way to handle this? I can't install anything since I'm not an admin, and the people who manage the machine probably won't do it for me anyway. Could I just create an alias in my .profile which goes something like: alias md5="md5sum"
? That way, when the script runs on Box 3, it'll execute md5 file.txt
but the system will really execute md5sum file.txt
since I created the alias.
Thoughts? Better ideas? :)
Upvotes: 2
Views: 3894
Reputation: 5722
I don't know what shell you're using. This is for bash:
#!/bin/sh
md5=$(which md5)
if [ ! "${md5}" ] ; then
md5=$(which md5sum)
if [ ! "${md5}" ] ; then
echo "neither md5 nor md5sum found"
exit 1
fi
fi
${md5} $0
Upvotes: 2
Reputation: 11
There are many possible solutions, as is often the case. Perhaps the following script, called somesum(1) would suffice ...
#!/bin/sh
# ident "@(#)somesum.sh: Find a command to do a checksum of a file"
################################################################################
export CMD
CMD=''
# if can find the command in the search path and CMD is not set,
# set CMD to the command name ...
[ "$CMD" = '' -a -f "`which md5 2>/dev/null`" ] && CMD=md5
[ "$CMD" = '' -a -f "`which md5sum 2>/dev/null`" ] && CMD=md5sum
################################################################################
# if command was found execute it else complain could not find desired commands
if [ "$CMD" != '' ]
then
$CMD $*
else
echo could not find md5sum or md5 1>&2
fi
exit
Or installing the preferred command on the other platforms in your own search path; or using the hostname(1) command to figure out which platform you are on. I am assuming you are on a platform that has the Bash shell (or ksh/pdksh/bash/...) in the example.
Upvotes: 1