Skip to content

Instantly share code, notes, and snippets.

@brunoborges
Last active September 12, 2025 18:13
Show Gist options
  • Save brunoborges/745fc63a6e1b500b0cc6a2e33fcaad89 to your computer and use it in GitHub Desktop.
Save brunoborges/745fc63a6e1b500b0cc6a2e33fcaad89 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# check-jvm-env-precedence.sh
# Pairwise precedence test for: _JAVA_OPTIONS, JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS
set -euo pipefail
say() { printf "%s\n" "$*"; }
hr() { printf "%s\n" "----------------------------------------"; }
# Tiny source-file program
cat > Test.java <<'EOF'
public class Test {
public static void main(String[] args) {
System.out.println("foo=" + System.getProperty("foo"));
}
}
EOF
# Run java with exactly two env vars set, the third removed,
# and also remove any inherited values from the parent shell.
test_pair() {
local A="$1" B="$2"
local aval="from-${A}" bval="from-${B}"
local out val
out="$(
env -u _JAVA_OPTIONS -u JAVA_TOOL_OPTIONS -u JDK_JAVA_OPTIONS \
"${A}=-Dfoo=${aval}" \
"${B}=-Dfoo=${bval}" \
java Test.java 2>&1 || true
)"
val="$(printf "%s\n" "$out" | awk -F'=' '/^foo=/{print $2; exit}')"
if [[ "$val" == "$aval" ]]; then
echo "$A"
elif [[ "$val" == "$bval" ]]; then
echo "$B"
else
say "WARN: ${A} vs ${B} produced unexpected output:"
say "$out"
echo "unknown"
fi
}
rank_three() {
local -A wins=([_JAVA_OPTIONS]=0 [JAVA_TOOL_OPTIONS]=0 [JDK_JAVA_OPTIONS]=0)
for w in "$@"; do
[[ "$w" == "unknown" ]] && continue
(( wins["$w"]++ )) || true
done
{
printf "_JAVA_OPTIONS %d\n" "${wins[_JAVA_OPTIONS]}"
printf "JDK_JAVA_OPTIONS %d\n" "${wins[JDK_JAVA_OPTIONS]}"
printf "JAVA_TOOL_OPTIONS %d\n" "${wins[JAVA_TOOL_OPTIONS]}"
} | sort -k2,2nr | awk '{print $1}'
}
hr
say "Pairwise tests with a clean env each time:"
w1="$(test_pair _JAVA_OPTIONS JAVA_TOOL_OPTIONS)"
say "_JAVA_OPTIONS vs JAVA_TOOL_OPTIONS -> winner: $w1"
w2="$(test_pair _JAVA_OPTIONS JDK_JAVA_OPTIONS)"
say "_JAVA_OPTIONS vs JDK_JAVA_OPTIONS -> winner: $w2"
w3="$(test_pair JAVA_TOOL_OPTIONS JDK_JAVA_OPTIONS)"
say "JAVA_TOOL_OPTIONS vs JDK_JAVA_OPTIONS -> winner: $w3"
order=($(rank_three "$w1" "$w2" "$w3"))
hr
say "Final precedence, highest first:"
printf "1) %s\n" "${order[0]:-inconclusive}"
printf "2) %s\n" "${order[1]:-inconclusive}"
printf "3) %s\n" "${order[2]:-inconclusive}"
hr
say "Sanity check with all three set at once:"
env -u _JAVA_OPTIONS -u JAVA_TOOL_OPTIONS -u JDK_JAVA_OPTIONS \
_JAVA_OPTIONS='-Dfoo=from-_JAVA_OPTIONS' \
JAVA_TOOL_OPTIONS='-Dfoo=from-JAVA_TOOL_OPTIONS' \
JDK_JAVA_OPTIONS='-Dfoo=from-JDK_JAVA_OPTIONS' \
java Test.java
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment