tags:

views:

195

answers:

2

I get "command not found" error in Mac by the following command

md5sum *.java | uniq -d -w32

The reason is that Mac does not have -w option by default.

I would like to make Bash to do the following when the error occurs

  1. put g at the beginning of the first command
  2. put g at the beginning of a command which is after |

How can you make the error more useful?

[edit]

Problem: if Mac does not have the feature, I want use the features in coreutils. Therefore, the g in front of Mac's commands.

A: 

On Mac OS X works:

/sbin/md5 *.java | uniq -d

For gnu uniq see:

http://rudix.org/#coreutils

+2  A: 

You cannot use command_not_found_handle() because the commands do exist; they just return an error ($? != 0) because of unrecognized parameters.

In these kinds of situations you should explicitly control the commands issued with a platform-specific prologue at the very beginning of the script, making the minimum number of assumptions about parameters, e.g.:

# defaults - satisfies most platforms
MD5SUM=md5sum
UNIQ=uniq
# per-platform exceptions
if [ "$OS" == "MacOS" ] ; then
  # use GNU variants by prefixing with g
  MD5SUM="g $MD5SUM"  # or use the native program, MD5SUM=md5
  UNIQ="g $UNIQ"      # or use the native program, UNIQ=uniq
elif [ "$OS" == "SomeOtherOS" ] ; then
  MD5SUM=md5hash # e.g. this platform computes MD5 sums with md5hash
fi
...
# optionally cross-check for GNU variants on all platforms
#  does uniq support -w32? (no error on dry run?) if so, use it!
$UNIQ -w32 /dev/null 2>/dev/null && UNIQ="$UNIQ -w32"
# optionally perform one last validation before proceeding
die() { echo "FATAL: $*" >&2 ; exit $1 ; }
$UNIQ /dev/null >/dev/null   || die $? "uniq is missing or failing: $UNIQ"
$MD5SUM /dev/null >/dev/null || die $? "md5sum is missing or failing: $MD5SUM"
...
$MD5SUM *.java | $UNIQ -d


UPDATE

Note that it is also good practice, especially if your script will run as root, to not rely on $PATH -- you would want to specify the fully qualified locations for programs such as uniq or md5 or md5sum above, e.g. UNIQ=/bin/uniq, MD5SUM=/sbin/md5sum, etc.)

Cheers, V.


UPDATE2

To automatically prefix a bunch of commands with "g":

eval `for command in uniq md5sum grep sed ; do
  echo \`echo \$command | tr '[a-z]' '[A-Z]'\`=\"g \$command\"
done`
vladr
It seems that I have write the above code for each Unix command. What is the fast way to do that?
Masi
you don't have to do this for each command, only for the problematic ones. But if you really must: eval `for command in uniq md5sum grep sed ; do echo \`echo \$command | tr '[a-z]' '[A-Z]'\`=\"g \$command\" ; done`
vladr