Workaround for the different behaviour of the which command in Solaris and in Linux

by Bernd Schemmer November 2009

Homepage: http://www.bnsmb.de/



In Linux you can use the which command like this:

#!/bin/sh

SH_BINARY=`which sh`
if [ $? -ne 0 ] ; then
	echo "ERROR: sh not found. Exiting"
	exit 0
fi


With /bin/sh from Solaris this code does not work because the which command in Solaris always returns 0.

In a kornshell script (using /usr/bin/ksh) you can use the builtin command whence to get around this limitation, e.g.

#!/usr/bin/ksh

SH_BINARY=`whence sh`
if [ $? -ne 0 ] ; then
	echo "ERROR: sh not found. Exiting"
	exit 0
fi

But unfortunately whence is an internal command of ksh therfore it is not available for scripts executed by /bin/sh.

To get around this limitation the following code can be used in shell scripts for /bin/sh that should work in Solaris and in Linux:

#!/bin/sh

if [ `uname -s` = "SunOS" ] ; then
	which() {
		ksh whence $*
	}
fi

Using this code you can use which in your shell scripts and it will work in Linux and in Solaris.

Example script

#!/bin/sh
#
# example script for a workaround for the different behaviour of which in
# Solaris and Linux
#
# History
#	11.03.2008 v1.0.0 /bs
#       initial release
#

# only define the new which function if running under Solaris
##
#
if [ `uname -s` = "SunOS" ] ; then
	which() {
# use the switch -p to ignore ksh internal commands
		ksh whence -p $*
	}
fi

echo "This script is running now under `uname -s`"
while true; do
	printf "Enter the name of a script or binary (\"\" to exit): "
	read THISFILE
	[ "${THISFILE}"x = ""x ] && break
	WHICH_RESULT=` which ${THISFILE}`
	THISRC=$?
	echo "Result: \"${WHICH_RESULT}\" "
	echo "The RC is ${THISRC}"
done

Notes:

The shell /usr/xpg4/bin/sh in Solaris is a standards compliant shell which provides all the functionality of ksh.
But in most cases you use "#/bin/sh" in shell scripts written for various Unix Operating systems and therefore the features of /usr/xpg4/bin/sh are not available.

In OpenSolaris the which command does return a value not equal zero if the command is not found.