Set environment variable in shell script/access in Java program

做~自己de王妃 提交于 2019-12-01 11:30:45

问题


I want to set environment using shell scrip in Ubuntu 10.04 and want to access in java program. I have wrote shell script like this:

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

and my java program is :

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 shell script it works well, but in shell script it does not.


回答1:


How are you sourcing the script?

$./myscript.sh 

or

$source ./myscript.sh 

The second will set the environment variable to current shell. The java program looks ok.

EDIT: based on the comment

It was a problem related to subshell. A quick read is
What is the difference between executing a bash script and sourcing a bash script?




回答2:


What are you trying to do exactly?

Running JAVA=/home/ubuntu java SystemEnv works fine (i.e. it outputs "/home/ubuntu")

If you want to export environment variables to the parent process, you have to source it:

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


来源:https://stackoverflow.com/questions/10140182/set-environment-variable-in-shell-script-access-in-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!