Skip to content

Instantly share code, notes, and snippets.

@mvdkwast
Last active January 21, 2022 13:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvdkwast/1c79f26712d678482b176ffed5e1fbfb to your computer and use it in GitHub Desktop.
Save mvdkwast/1c79f26712d678482b176ffed5e1fbfb to your computer and use it in GitHub Desktop.
Switch jdk versions (bash + perl)
#!/usr/bin/env perl
use v5.28;
use Data::Dumper;
use Tie::IxHash;
my @jdk_paths = qw{~/.jdks /usr/lib/jvm};
my @jdks;
push @jdks, glob "$_/*-*" for @jdk_paths;
my $version = $ARGV[0];
unless ($version) {
say STDERR $_ for @jdks;
exit 1
}
my @matches = grep { $_ =~ m{.*/*-\Q$version\E} } @jdks;
if (@matches < 1) {
say STDERR "No matching versions. Available:";
say STDERR $_ for @jdks;
exit 1
}
if (@matches > 1) {
say STDERR "Multiple matching versions found: ";
say STDERR $_ for @matches;
exit 1
}
my $jdk = $matches[0];
say STDERR "Using $jdk";
my $p = $ENV{PATH};
my @expanded_paths;
for my $path (@jdk_paths) {
push @expanded_paths, $path;
my $x = glob $path;
push @expanded_paths, $x unless $x eq $path or !$x;
}
my $paths_rx = join '|', @expanded_paths;
my @v = grep ! m{/$paths_rx/}, split /[:]/, $p;
tie my %s, 'Tie::IxHash';
$s{$_}++ for @v;
say 'export PATH="' . $matches[0] . '/bin:' . join(':', keys %s) . '"';
say 'export JAVA_HOME=' . $matches[0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment