Set environment variable linux from java

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 – Linux Set Environment Variables Command

  1. Configure look and feel of shell.
  2. Setup terminal settings depending on which terminal you’re using.
  3. Set the search path such as JAVA_HOME, and ORACLE_HOME.
  4. Create environment variables as needed by programs.
  5. Run commands that you want to run whenever you log in or log out.
  6. Set up aliases and/or shell function to automate tasks to save typing and time.
  7. Changing bash prompt.
  8. Setting shell options.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux
Est. reading time 11 minutes

Two types of shell variables

  • Environment variables (GLOBAL): Typically, end-users shouldn’t mess with Environment variables as they are available system-wide, and subshells and child processes can access them. In certain scenarios, we can modify them as per our needs. For example, we set up a system-wide path for the JAVA app or PATH for searching binaries. In almost all cases, we use the export command to define or modify environment variables.
  • Shell and user-defined variables (LOCAL) : As the name suggests, these are defined by users and currently apply to the current shell session.

You can use the following commands to view and configure the environment.

Display current environment variables on Linux

The printenv command shows all or the given environment variables. Open the terminal prompt and then type:
printenv
printenv VAR_NAME
printenv PS1
printenv ORACLE_HOME
printenv JAVA_HOME
# use the grep command/egrep command to filter out variables #
printenv | grep APP_HOME
printenv | egrep ‘APP_HOME|DOCKER_HOME|NIX_BACKUP_HOST’

env command

The env command runs a Linux command with a modified environment. The syntax is:

Please note that If no command name is specified following the environment specifications, the resulting environment is displayed on screen. This is like specifying the printenv command as discussed earlier. For example:

How to set and list environment variables in Linux using set command

The env command/printenv command displays only the Linux shell environment variables. What if you need to see a list of all variables, including shell, environment, user-defined shell functions? Try the following set command for printing environment variables:
set
set | grep BASH
Here is what we see:

The $PATH defined the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. The $PS1 defines your prompt settings. See the list of all commonly used shell variables for more information. You can display the value of a variable using the printf command or echo command:

Outputs from the last command displaying my home directory location set by the $HOME environment variable on Linux:
/home/vivek

Источник

Environment Variables

Many operating systems use environment variables to pass configuration information to applications. Like properties in the Java platform, environment variables are key/value pairs, where both the key and the value are strings. The conventions for setting and using environment variables vary between operating systems, and also between command line interpreters. To learn how to pass environment variables to applications on your system, refer to your system documentation.

Querying Environment Variables

On the Java platform, an application uses System.getenv to retrieve environment variable values. Without an argument, getenv returns a read-only instance of java.util.Map , where the map keys are the environment variable names, and the map values are the environment variable values. This is demonstrated in the EnvMap example:

With a String argument, getenv returns the value of the specified variable. If the variable is not defined, getenv returns null . The Env example uses getenv this way to query specific environment variables, specified on the command line:

Passing Environment Variables to New Processes

When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application’s virtual machine process. The application can change this set using ProcessBuilder.environment .

Platform Dependency Issues

There are many subtle differences between the way environment variables are implemented on different systems. For example, Windows ignores case in environment variable names, while UNIX does not. The way environment variables are used also varies. For example, Windows provides the user name in an environment variable called USERNAME , while UNIX implementations might provide the user name in USER , LOGNAME , or both.

Источник

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

Источник

Читайте также:  Mac os как отключить микрофон
Оцените статью