Well, I have access to
ksh on SunOS 5.10, and for it,
case seems to work well:
Code:
FILE1="/path/to/some/file"
FILE2="/path/to"
# +u case sensitive, -u is case insensitive
typeset +u TEMP1 TEMP2
TEMP1="$FILE1"
TEMP2="$FILE2"
case "$TEMP1" in
"$TEMP2") echo "FILE1 ($FILE1) is the same as FILE2 ($FILE2)" ;;
"${TEMP2%/}/"*) echo "FILE1 ($FILE1) has prefix FILE2 ($FILE2)" ;;
esac
case "$TEMP2" in
"${TEMP1%/}/"*) echo "FILE2 ($FILE2) has prefix FILE1 ($FILE1)" ;;
esac
Note that the above uses
${TEMP%/}/ which literally means the value of TEMP, with the trailing slash removed if there is one, with a trailing slash added. Even old Korn shells should support that expression. (I recommend you check, though.)
You'll want to use that, if you do not want
/some/path to match
/some/path2/file . Otherwise, just use plain
$TEMP .
If you are working on a truly ancient Unix, you can always work around the problems by using
wc for length,
cut for string manipulation, and optionally
tr for case conversion:
Code:
FILE1="/some/path"
FILE2="/some/other/path"
LEN1=`echo -n "$FILE1" | wc -c | tr -cd 0-9`
LEN2=`echo -n "$FILE2" | wc -c | tr -cd 0-9`
if [ $LEN1 -gt 0 ] && [ $LEN2 -gt 0 ]; then
TEMP1="`echo -n "$FILE1" | tr a-z A-Z | cut -b1-$LEN2`"
TEMP2="`echo -n "$FILE2" | tr a-z A-Z | cut -b1-$LEN1`"
if [ ":$TEMP1" == ":$TEMP2" ]; then
echo "FILE1 ($FILE1) is a prefix of FILE2 ($FILE2) or vice versa."
fi
fi
The above does case insensitive comparison; if you want case sensitive comparison, just replace the
| tr a-z A-Z | above with
| .
Old shells don't always support
$(cmd) subshells, so I use the ancient but equivalent
`cmd` instead.
Note that the lengths are intentionally swapped, so that TEMP1 and TEMP2 end up being the same length. I put the colons into the compared patterns just in case your shell does not compare empty strings properly.