So I have a java process that is doing some automation. One of the things it has to do is find the JDK home on random machines.
So I wrote a shell script to try and find the JDK home assuming that javac
is on the path.
While testing this shell script locally I came across some rather strange behavour which I would like to understand.
The strange behaviour boils down to the which
command behaving rather oddly. The snippet of the script that I am at a loss to explain starts with
#/bin/sh
...
if [ -z "$JAVA_HOME" ]; then
javac -version
which javac || echo "rv=$?"
javaExecutable="`which javac`"
...
(I added the javac -version
and which javac || echo "rv=$?"
just to check I had a valid PATH in the forked process)
If I use sh -x
to start the forked process then I get the following output:
+ '[' -z '' ']'
+ javac -version
javac 1.8.0_11
+ which javac
+ echo rv=1
rv=1
++ which javac
+ javaExecutable=
If I replace which
with the following function
_which() {
oldIFS="$IFS"
IFS=':'
for p in $PATH
do
if [ -x "$p/$1" ]; then
echo "$p/$1"
IFS="$oldIFS"
return 0
fi
done
IFS="$oldIFS"
return 1
}
Then everything works as I would expect.
If I invoke my original script from the command line directly... everything works
If I invoke my original script via ssh localhost sh -x PathToScript
... everything works