Export java home linux

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 in Ubuntu 18.04 and 20.04 LTS

A large number of Java-based programs require Java Runtime Environment (JRE) to run smoothly regardless of operating systems. For development purposes, most IDEs like Eclipse and NetBeans require Java Development Kit (JDK) installed on the machine. Whether you are a newbie developer looking forward to learning development or perhaps an application you have installed requires you to have Java installed on your system, we have you covered. Setting up of JAVA_HOME path is quite easy.

In this tutorial, we are going to learn how to install JDK on Ubuntu 18.04 and 20.04 and then set up the java home path. Let’s start by installing the JDK first.

Install OpenJDK on Ubuntu

Note: Make sure that you have updated the Advanced Package Tool (APT) before you move forward to install OpenJDK.

Press Ctrl + Alt + T to open the terminal and enter the following command mentioned in the box. You can either install OpenJDK 8 or the newer versions OpenJDK 11 or OpenJDK 14:

Install OpenJDK 8

Install OpenJDK 11

Install OpenJDK 14

You will be prompted to enter your sudo password to continue with the installation.

Once you’ve entered that, wait for the system to finish the installation and then move onto step 2.

Set JAVA_HOME Path

All you have to do now is to set the “JAVA_HOME” and “PATH” environment variables and then you are done. Enter the following commands to set your environment variables. Make sure that your environment variables point to a valid installation of JDK on your machine. For Ubuntu 18.04, the path is /usr/lib/jvm/java-8-openjdk-amd64/

To check whether your JAVA_HOME path has been successfully saved, enter the following command to check.

The value stored in the JAVA_HOME variable will be displayed on the terminal as you can see in the screenshot

Add JAVA bin directory to the PATH variable

Like we have added JAVA_HOME path, we will now update the PATH variable as well. To do that, enter the following command on the terminal.

This will append the java bin directory to the existing PATH variable. You can also check the PATH variable by entering the following command

Test JAVA setup

You have successfully installed OpenJDK on your machine. You can verify your installation by entering the following command on your terminal.

Through this simple tutorial, you have now configured the JAVA_HOME variable in your operating system. You can now easily run java based applications as well as development environments on your machine. Let us know in comments if you faced any issues while implementing this tutorial.

Читайте также:  Создать iso образ флешки mac os

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

How to set JAVA_HOME and PATH in Linux? Example

Like in the previous article, I explained a Maven issue (invalid target release: 1.7, 1.8) related to the Java version, which occurred even though the correct version of Java was installed on the machine, but JAVA_HOME was pointing to an older version.

Unfortunately, When you install Java on Linux or Windows, this environment variable is not set automatically. You need to do it yourself. Java developers like me always set mandatory environment variables like JAVA_HOME, PATH, and CLASSPATH on the login scripts executed by the shell when you log in to Linux like bash_profile.sh , but you can also set JAVA_HOME into /etc/profile for all users.

I’ll show you steps on how to find the location of Java and how to set up the JAVA_HOME in Linux in this article, and these steps should also work with any Linux or Java version like Ubuntu, RedHat, CentOS, SUSE, ArchLinux, Debian, Fedora, etc.

Though I strongly encourage every Java developer to learn Linux, it’s a really important skill and serves you for a long time. If you decide to improve your Linux skill this year, I suggest you take a look at these best online Linux courses, which are both short and sweet and also explains all important details.

1. Steps to set JAVA_HOME in Linux

1) The first step is to find the location where Java is installed on your Linux machine. To check that open putty and connect to your Linux server and type the following command

where options include:
-d32 use a 32-bit data model if available
-d64 use a 64-bit data model if available
-server to select the «server» VM

It means Java is installed and added to your PATH, so half of the job is done already. All you need to is find the location of JDK, which you can find either by printing PATH as follows

You can see that JDK is installed on «/usr/sun/jdk/v1.6.0_16-64bit».

2) Add the following line of your .bash_profile file if you want to set JAVA_HOME for yourself or /etc/profile if you want to set JAVA_HOME for all user

That’s it you are done. Though don’t forget to open another shell window by typing bash , csh , or ksh . The new environment variable will not be added to an existing shell, you need to open a new shell window.

Also, if you use bash shell then adding into

/.bash_profile makes sense, if you use csh (C shell) then add JAVA_HOME into

/.csh_profile, and similarly for ksh (K shell) add JAVA_HOME into

They are hidden files in your home directory in Linux, that’s why they had prefix dot (.) in their name. You can use «ls — alrt» command to see them.

Here is a sample /etc/profile file with JAVA_HOME and PATH variable defined for your reference:

By the way, if you don’t see Java installed on your machine, then download the Linux version of Java from Oracle’s website and install it.

Once you are done with installation just find the folder where JDK is installed and follow the steps given above to set JAVA_HOME for your Linux environment.

For applications, JAVA_HOME is generally referred to on the start script. It’s bad practice to refer to the hardcoded path of Java installation in scripts, you will never find Tomcat, Maven, Eclipse, NetBeans, or IntelliJ doing that because then when you update to a new Java version they won’t be able to use it until you change their start script.

Using JAVA_HOME makes it easy to switch to a different or new Java version. See these free Java development courses to learn more about the core concepts of Java in detail. It’s updated for Java 11 and also not very expensive, I just bouthbought11 a couple of days ago.

2. Why should you set JAVA_HOME in Linux

Even though many developers know about JAVA_HOME, they don’t set it in their environment due to various reasons. I strongly recommend you to set JAVA_HOME , PATH , and CLASSPATH for your development environment. Here are some reasons why you set JAVA_HOME in Linux

1) It’s easy to upgrade JDK without affecting your application startup and config file, which points to JAVA_HOME . You just need to download a new version and make sure your JAVA_HOME points to the new version of Java. This is the best benefit of using an environment variable or links.

2) The JAVA_HOME variable is short and concise instead of the full path to the JDK installation directory.

3) JAVA_HOME variable helps your program achieve platform independence like if your startup script uses JAVA_HOME, then it can run on Windows and UNIX without any modification; you just need to set JAVA_HOME on the respective operating system.

4) The JAVA_HOME is standard, which means other tools that need Java, like Maven, Eclipse can refer to this variable without having any knowledge of where Java is physically installed on your machine, which is obviously different in different user’s machines. JAVA_HOME allows everybody to access Java in a common and standard way.

I also suggest joining Java Fundamentals: The Java Language course on Pluaralsight to learn more about Java fundamentals like this one.

That’s all about how to set the JAVA_HOME environment variable in Linux. I have also touched base on why you should do it, which is probably more important. Many tools like Maven and IDEs like Eclipse and Netbeans use this variable to locate the JDK binaries installed on this machine, hence it’s better to set this up. If you face any problem while setting and using the JAVA_HOME environment variable, feel free to ask. I’ll be glad to help you out.

Читайте также:  Windows graphics capture obs курсор

Источник

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

Источник

Читайте также:  Asrock не устанавливается windows с флешки
Оцените статью