I came across a script that has the line:
java_version=$($JAVA_HOME/bin/java -version 2>&1 | awk -F '"' '/version/ {print $2}' | cut -d '_' -f 1,3)
followed by the test:
if [[ -n "$java_version" ]]; then
...
The test when called from the command line succeeds. When called from Java application fails.
Some useful notes:
- The first line in the script is
#!/usr/bin/env bash
. - The fact that the test succeeds when called from the command line means
java_version
is not empty. For further verification, Iecho
'd right before the test the value ofjava_version
into some external file and found the value there. - I changed the double brackets to singular and the test succeeded in both calling the script from the command line and the Java application.
- I'm running GNU/Linux Ubuntu 18.04, bash version 4.4.20, Java 8 (Oracle JDK).
Any ideas on what might cause this change of behavior?
[ ]
is the POSIX test, whereas[[ ]]
contains additional functionality inbash
,zsh
, andksh
. What shell does Java use? Perhapsstrace
might reveal how the script is called from Java. – Christopher Oct 21 '19 at 11:37[[
isn't standard comes first to mind, but if the script gets run with a shell that doesn't support it, you should get an error – ilkkachu Oct 21 '19 at 11:48/bin/sh scriptname.sh
– ilkkachu Oct 21 '19 at 11:50else
part). – joker Oct 21 '19 at 11:50exec()
, i.e../scriptname.sh
, see e.g. here. You could put something likeecho "bash version = $BASH_VERSION"
in the script to see if it really runs with Bash – ilkkachu Oct 21 '19 at 11:53[ ]
is sufficient; there's no purpose in using[[ ]]
for the simple test. – Christopher Oct 21 '19 at 11:57sh
. I guess this explains why[[ ]]
doesn't work. – joker Oct 21 '19 at 13:24