- How to Set JAVA_HOME / PATH variables Under Linux Bash Profile
- Set JAVA_HOME / PATH for a single user
- Set JAVA_HOME / PATH for all user
- Установка Java в Linux
- Чем отличается JDK от JRE
- Установка Java в Linux своими руками
- Установка Java в Ubuntu
- JRE и JDK
- Установка Java в ArchLinux
- Установка Java в CentOS
- Выбор версии Java
- Ubuntu
- ArchLinux
- CentOS
- Настройка переменных окружения
- Выводы
How to Set JAVA_HOME / PATH variables Under Linux Bash Profile
I just need a help to show me how to setup java path on Linux. How can I set JAVA_HOME and PATH variables for every user under my Linux system?
/.bash_profile is a startup script which generally runs once. This particular file is used for commands which run when the normal user logs in. Common uses for .bash_profile are to set environment variables such as PATH, JAVA_HOME, to create aliases for shell commands, and to set the default permissions for newly created files.
Set JAVA_HOME / PATH for a single user
Login to your account and open .bash_profile file
$ vi
/.bash_profile
Set JAVA_HOME as follows using syntax export JAVA_HOME=
. If your path is set to /usr/java/jdk1.5.0_07/bin/java, set it as follows:
export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java
Set PATH as follows:
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
Feel free to replace /usr/java/jdk1.5.0_07 as per your setup. Save and close the file. Just logout and login back to see new changes. Alternatively, type the following command to activate the new path settings immediately:
$ source
/.bash_profile
Verify new settings:
$ echo $JAVA_HOME
$ echo $PATH
Tip: Use the following command to find out exact path to which java executable under UNIX / Linux:
$ which java
Please note that the file
/.bashrc is similar, with the exception that
/.bash_profile runs only for Bash login shells and .bashrc runs for every new Bash shell.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Set JAVA_HOME / PATH for all user
You need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users:
# vi /etc/profile
Next setup PATH / JAVA_PATH variables as follows:
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
Save and close the file. Once again you need to type the following command to activate the path settings immediately:
# source /etc/profile
OR
# . /etc/profile
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I believe this is wrong !
1) In my case I did all you said for .bash_profile, however, running which java still shows old java path (crappy java that comes with linux fedora 7)
2) I tried the same to set /etc/profile but I believe you provided wrong sintax
Could somebody provide correct sintax for seting java path in /etc/profile or whatever as long as my which java will show my newest java?
The correct syntax is as show below,
I have read lots of user posting at various pages and none of them would work. Finally, I found a way to do this correctly and hope this will help to some of you.
Follow the simple steps:
1. To set the environment variables :
echo ‘export JAVA_HOME=/opt/jdk1.5.0_12’ > /etc/profile.d/jdk.sh
echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh
2. You have to source the file you just created by typing:
source /etc/profile.d/jdk.sh
3. Test if Java environment is successfully installed by typing in this in the shell:
java -version
when I type these above script or command my terminal say “Permission denied”.
Tell the answer
Thanks in Advnace
use “sudo ” if you’re using ubuntu.
else try using “su”
Try googling in case both don’t work 😀
Thank you for solution. This worked perfectly for me in Linux.
Thank you. This worked. Nothing else did!
Thanks .
That’s work for me and after testing the version it shows the new version. The other answers couldn’t work for me 🙁
Thank you for this answer, it worked for me. Best regards, Kevin
I have read lots of posting and none of them worked well. This one did so I decided to try to post it hopefully somebody else wont have to get this frustrated to get such a simple thing done.
1. To set the environment variables:
echo ‘export JAVA_HOME=/opt/jdk1.5.0_12’ > /etc/profile.d/jdk.sh
echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh
2. You have to source the file you just created by typing:
source /etc/profile.d/jdk.sh
3. Test if Java environment is successfully installed by typing in this in the shell:
$ java -version
java version “1.6.0_03”
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Server VM (build 1.6.0_03-b05, mixed mode)
You can also use which java to test:
$ which java
/usr/java/jdk1.6.0_03/bin/java
hay it is working…but how can i set permentally set…the java path
its working only one terminoal only…
i need permentally java path setting
help me
Setting java class path in Linux:
I have faced the same problem . How to set it permanently. please help me
review of these lines:
……
1. To set the environment variables:
2. You have to source the file you just created by typing:
I have the same problem, something at the startup doesn´t work well in /etc/profile from the /etc/profile.d/*.sh are called.
To resolve this, put the exports directly at the end of the /etc/profile file..
and you have permanently set them, JAVA_HOME and JRE_HOME
+1 Made my day. Thank you.
Thank you, worked for me.
my last reply is using mistakenly 2 different versions of jdk. Reference to jdk in point 1 and 3 should be the same as well as in the testing part
My last 2 postings use 2 different jdk by accident. References to jdk should be the same.
For the sake of consistance, please use (of course substitute your java directory in place of mine /usr/lib/java/jdk….):
echo ‘export JAVA_HOME=/usr/lib/java/jdk1.6.0_03′ > /etc/profile.d/jdk.sh
istead of
echo ‘export JAVA_HOME=/opt/jdk1.5.0_12′ > /etc/profile.d/jdk.sh
at the terminal. You type 2 comand to apply the env for bath shell.
#source /etc/profile
#/etc/init.d/x11-common restart
bas se nesto gnjavim sa serverom ali ovaj tvoj post je dosao k’o kec na desetku.
Thanks for your post, it does exactly what it says on the tin. Just what I needed.
I use the IDE 6 with netbeans to create a simple application and I build it and when I navigate to its dist location through the terminal and type:
>> java -jar addition.jar
it gives me this message could you please help me to solve this problem:
Exception in thread “main” java.lang.NoClassDefFoundError: javax/swing/GroupLayout$Group
i need to run my application with jdk,jmf and jakarta tomcat hw do i go about setting the environment variables?
I think it’s worth mentioning that on most Linux systems, there is a convenient facility to manage different java implementations – its called “alternatives” – depending on the version of your system it may be:
/usr/sbin/alternatives –config java
or
sudo update-alternatives –config java
Rather than log out and back in you can run your new bash profile with a single period:
$ cd
$ . .bash_profile
How to install JDK (Java Development Kit) on Linux, In my case Fedora 10?
1. Log in as root:
su-
type in your password and the prompt will change from $: to #:
2. Download JDK from here:
http://java.sun.com/javase/downloads/index.jsp
As of time of this post, the most current JDK was:
Java SE Development Kit (JDK) 6 Update 11.
Select file jdk-6u11-linux-i586.rpm.bin to download it by providing your operation system and multilanguage.
3. Go to directory where you downloaded the file (In my case it is Download directory in /home/username/Download/)
The file is called jdk-6u11-linux-i586.rpm.bin
4. Change mode of this file so you can execute it by issuing:
chmod 755 jdk-6u11-linux-i586.rpm.bin
5. run the file by issuing:
./jdk-6u11-linux-i586.rpm.bin
This will show acceptance agreement, press untill you reach end they type “yes” and press and the installation will start.
6. When installation completes, you will need to find the actuall location of your JDK and make Fedora accept your choice. You can do this by issuing:
updatedb;locate javac |grep bin
This will list several options (at least two, the default one shipped with fedora, and the one you downloaded from Java Sun in step 2 above. In my case, I get:
[root@DRACHE Download]# locate javac |grep bin
/usr/bin/javac
/usr/java/jdk1.6.0_10/bin/javac
/usr/java/jdk1.6.0_11/bin/javac –this is what we downloaded in step 2 above, we want to make make Fedora recognaze this jdk.
7. To make Fedora recognaze your jdk (JVM), use alternatives command and issue following 3 commands one after another:
alternatives —install /usr/bin/java java /usr/java/jdk1.6.0_11/bin/java 100
alternatives —install /usr/bin/jar jar /usr/java/jdk1.6.0_11/bin/jar 100
alternatives —install /usr/bin/javac javac /usr/java/jdk1.6.0_11/bin/javac 100
These 3 commands set your java, jar and javac commands. You can use same to set other java executables if you want.
8. Configure alternatives to use the jdk you downloaded above in step 2 rather than the java shipped with Fedora by issuing:
/usr/sbin/alternatives —config java
This will present you with at least 2 options (one is the default jdk shipped with Fedora, other is jdk you downloaded in step 2 above). In my case, I have somehting like this but in your case, this can look different:
/usr/sbin/alternatives —config java
There are 6 programs which provide ‘java’.
Enter to keep the current selection[+], or type selection number:
9. Choose the one you downloaded in step 2 above and press . In my case, that is option 4.
10. repeat the same for jar and javac command as:
/usr/sbin/alternatives —config jar
/usr/sbin/alternatives —config javac
11. Issue:
java -version
and you will see something like this:
[dino@DRACHE Download]$ java -version
java version “1.6.0_11”
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Server VM (build 11.0-b16, mixed mode)
Now you are done. Hope this helps 🙂
Mustafa Buljubasic
Thanks to article from Angsuman Chakraborty from August 7th, 2007
Thanks Mustafa, It worked like a charm for me , am using RHEL5
Источник
Установка Java в Linux
В этой статье речь пойдёт о проприетарной версии Java. Часто происходят ситуации, когда пользователь пытается открыть какую-либо программу на Java, а она либо вообще не запускается, либо пытается это сделать с помощью OpenJDK (Java Development Kit). Но вместо результата вы получаете кучу ошибок (как например с Minecraft). В данных ситуациях вам, скорее всего, поможет установка Java от Oracle.
Я вам расскажу, как установить JRE (Java Runtime Environment) и JDK (Java Development Kit) 8 версии на такие дистрибутивы, как Ubuntu, CentOS и Arch, а также как выбрать нужную среду по умолчанию.
Чем отличается JDK от JRE
- JRE — Java Runtime Environment — это среда выполнения Java. Предназначена для обычного использования. Позволяет запускать приложения, написанные на языке Java.
- JDK— Java Development Kit — стандартная версия платформы Java, предназначенная для разработки. Это специальный пакет разработчика, в который входят документация, различные утилиты, компилятор, библиотеки классов, а также сама JRE.
Установка Java в Linux своими руками
Скачать архив с необходимой вам версией вы можете с официального сайта. Далее вам надо перенести его в желаемую директорию и распаковать. Рекомендую /opt/java, далее она и будет использоваться. Сделайте это, используя следующие команды:
sudo tar -xzf /opt/java/jre*.tar.gz
Где «*» — версия Java.
Загрузите архив со средствами разработчки с официального сайта компании Oracle. Также перенесите его в желаемую директорию и распакуйте:
sudo tar -xzf /opt/java/jdk*.tar.gz
Установка Java в Ubuntu
JRE и JDK
Для установки проприетарной Oracle Java вам необходимо добавить репозиторий, обновить индексы пакетов и установить Java. В Ubuntu, начиная с 18 релиза, это делается автоматически после добавления репозитория.
Внимание! Будут установлены как JRE, так и JDK. Сначала добавим репозиторий и обновим списки пакетов:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
В процессе установки необходимо будет принять лицензионное соглашение:
sudo apt-get install oracle-java8-installer
Установка Java в ArchLinux
В официальных репозиториях есть только OpenJDK. Поэтому придётся воспользоваться пакетом из AUR(вы можете, конечно, руками установить Java от Oracle, но AUR проще). Установка производится всего одной командой:
JDK так же можно установить, используя AUR. Просто выполните команду:
Установка Java в CentOS
Для RHEL, Fedora, Cent OS, OpenSUSE есть официальный RPM-пакет, который вы можете скачать с официального сайта. Чтобы установить пакет из терминала, воспользуйтесь этой командой:
sudo rpm -i /путь/к/файлу/jre-*.rpm
где «*» — версия Java. Или же примените любую графическую утилиту.
Средства для разработчика вы можете скачать на сайте Oracle, ссылка на который есть в верху статьи. Для установки из терминала, используйте команду:
Где «*» — версия Java. «
» — указывает, что путь начинается.
Выбор версии Java
Ubuntu
Для переключения на 8 версию Java используйте следующую команду:
sudo update-java-alternatives -s java-8-oracle
Чтобы автоматически установить переменные среды, воспользуйтесь командой:
sudo apt-get install oracle-java8-set-default
Или же вы можете установить альтернативы сами. Делается это с помощью следующих команд:
sudo update-alternatives —install /usr/bin/java java / usr / lib / jvm / java-8-oracle/bin/java 1
sudo update-alternatives —install / usr / bin / javaс javaс / usr / lib / jvm / java-8-oracle / bin / javaс 1
sudo update-alternatives —install / usr / bin / javaws javaws / usr / lib / jvm /java-8-oracle / bin / javaws 1
Теперь осталось выбрать версии исполняемых файлов java, javaws и javac, которые будут использоваться по умолчанию:
sudo update-alternatives —config java
sudo update-alternatives —config javac
sudo update-alternatives —config javaws
ArchLinux
Для начала просмотрите список установленных сред:
Затем установите необходимую вам:
archlinux-java set имя_среды
archlinux-java set java-8-jre/jre
CentOS
Выбрать необходимую среду можно с помощью команд, данных ниже (так же, как и в Ubuntu). Вам нужно будет просто выбрать цифру, соответствующую номеру версии:
sudo update-alternatives —config java
sudo update-alternatives —config javac
sudo update-alternatives —config javaws
Настройка переменных окружения
Чтобы настройки были доступны для всех пользователей, будем использовать файл /etc/profile. Откройте его для редактирования любым текстовым редактором с помощью команды sudo и добавьте в конец следующие строки:
- export JAVA_HOME=/opt/java/jdk*/
- export JRE_HOME=/opt/java/jdk*/jre
- export PATH=$PATH:/opt/java/jdk*/bin:/opt/java/jdk*/jre/bin
- Вместо пути по умолчанию /opt/java укажите тот, который использовали;
- Если вы используете не JDK, а JRE, то в пути у вас так же будет не «jdk*», а «jre*»;
- «*» — версия Java, которая у вас установлена.
Выводы
В данной статье мы подробно разобрали процесс установки и настройки Java в различных дистрибутивах Linux. Если остались вопросы, спрашивайте в комментариях!
Источник