- linux-notes.org
- Установка переменных JAVA_HOME / PATH в Unix/Linux
- One thought on “ Установка переменных JAVA_HOME / PATH в Unix/Linux ”
- Добавить комментарий Отменить ответ
- 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
linux-notes.org
Не знаете как установить переменные JAVA_HOME и PATH для каждого пользователя в соответствии с вашей системой Linux? Тогда эта статья «Установка переменных JAVA_HOME / PATH в Linux» именно для Вас. Я напишу ее в качестве заметки, чтобы потом быстренько вспомнить и прописать Java_Home и Path на ОС для каждого пользователя ( если понадобится).
Установка переменных JAVA_HOME / PATH в Unix/Linux
/ .bash_profile является сценарий запуска, который обычно выполняется один раз. Это конкретный файл используется для команд, которые выполняются, когда нормальные входе пользователя в систему. Common использует для .bash_profile должны установить переменные окружения, такие как PATH, JAVA_HOME, чтобы создать псевдонимы для команд оболочки, и установить права доступа по умолчанию для вновь создаваемых файлов.
Установка JAVA_HOME / PATH для одного пользователя
Зайдите в свой аккаунт (учетную запись) и откройте файл .bash_profile в любом редакторе:
Установите JAVA_HOME как показано используя синтаксис export JAVA_HOME=
. Если ваш путь такой как у меня /usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java, то тогда пропишите:
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java
Чтобы установить PATH пропишите:
Замените путь /usr/java/jdk1.5.0_07 на свой. Сохраните и закройте файл. Просто выйдите и зайдите обратно (перелогиньетсь), чтобы увидеть изменения или чтобы все изменения вступили в силу, выполните команду:
Чтобы проверить отображение новых настроек, используйте команды:
Совет: Используйте следующую команду, чтобы узнать точный путь Java под UNIX / Linux:
Пожалуйста, обратите внимание, что файл
/.bashrc похож на
/.bash_profile но работает только для оболочки Bash и .bashrc работает для каждой новой Bash оболочки.
Установка JAVA_HOME / PATH для всех пользователей
Вам нужно добавить строки в глобальный файл конфигурации в /etc/profile ИЛИ /etc/bash.bashrc чтобы внести изменения для всех пользователей:
Добавьте переменные PATH / JAVA_PATH следующим образом:
Сохраните и закройте файл. Еще раз вам нужно ввести следующую команду, чтобы немедленно активировать настройки:
Но если не будет работать, есть еще 1 способ прописать все это дело! Сейчас я покажу как это можно сделать.
1. Устанавливаем переменные среды:
2. Выполните команду чтобы перезапустить все только что прописанные настройки:
3. Тест, если среда Java успешно установлена, введите команду в терминале чтобы проверить работу:
Установка переменных JAVA_HOME / PATH в Unix/Linux завершена.
One thought on “ Установка переменных JAVA_HOME / PATH в Unix/Linux ”
Спасибо за гайд, работает как часы. Первых пунктов до bash_profile включительно хватило. Версия х64. Пути и названия свои. Проверил еще javac -version. Вопрос к автору. Где эту информацию искать на сайте оракла?
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Источник
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
Источник