EDITED
The question was more about bash script them java environment and thanks for those whom had the patience and spare the time to reply me. I am much obliged.
As for the Java environment I started using sdkman. When I started this little script I was actually looking for something just like that, I was considering doing something similar. Whoever is looking for an answer to my question I recommend using the tool. It doesn't matter if you get yourself your own script, I urge you to git it a try.
The sdkman will care for language version installation, side lunges need (like maven, gradle and kotlin) as well as environment variables.
Original Question
I'm building a bash script to set both the JAVA_HOME and the PATH of the user automatically considering the version of the active java, however for some reason PATH is not being built correctly, it is adding blanks instead of ": ", could anyone tell me why?
Below the script.
Thanks!
#!/bin/bash
export JAVA_HOME=$(dirname $(dirname `readlink -f /etc/alternatives/java`))
IFS=':';
for i in $PATH;
do
JAVA1=$i/bin/java
JAVA2=$i/java
if [ -d "$i" ];
then
if [ ! -L "$JAVA1" ] && [ -x "$JAVA1" ] || [ ! -L "$JAVA2" ] && [ -x "$JAVA2" ];
then
echo "dropping path: $i";
else
NEW=$NEW:$i
fi
fi
done
PATH=$NEW:$JAVA_HOME/bin
echo
echo "Final:"
echo $PATH
Sample output:
$ ./java_home_setter.sh
dropping path: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin
Final:
/usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin /usr/games /usr/local/games /snap/bin /usr/lib/jvm/java-8-openjdk-amd64/bin
Best Answer
Thast's because you have altered IFS variable to use ':'
so when its output your variable its replaced with default output field separator which is 'space' thinking that ':' is input field separator .
you have take backup of it before using IFS like below :
after 'for' loop is done , restore it :
Also remove the ':' which starts with no path preceding that
Your script should be like :