Set environment variable in script / access shell in Java program

I want to install the environment using a shell in Ubuntu 10.04 and want to access in a java program. I wrote a shell script as follows:

#! /bin/sh export JAVA=/home/ubuntu echo "Variable $JAVA" 

and my java program:

 import java.util.Map; public class SystemEnv { public static void main(String[] args) { Map<String, String> variables = System.getenv(); for (Map.Entry<String, String> entry : variables.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); System.out.println(name + "=" + value); } System.out.println(System.getenv(("JAVA"))); } } 

When I execute this command without a shell script, it works well, but in a shell script it does not work.

+1
source share
2 answers

How do you use a script?

 $./myscript.sh 

or

 $source ./myscript.sh 

The second sets the environment variable to the current shell. The java program looks fine.

EDIT: based on comment

This was a subshell issue. Quick read - What is the difference between running a bash script and finding a bash script?

+4
source

What are you trying to do for sure?

Running JAVA=/home/ubuntu java SystemEnv works fine (ie displays "/ home / ubuntu")

If you want to export environment variables to the parent process, you must specify it:

 source ./myscript.sh . ./myscript.sh # Alternative form 
+1
source

Source: https://habr.com/ru/post/913195/


All Articles