Set environment variable in shell script/access in Java program
Asked Answered
L

2

1

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.

Leilaleilah answered 13/4, 2012 at 11:45 Comment(2)
Please show the shell script in its entirety (i.e. including the java command you use to run your code). Also, when you say it doesn't work, what exactly are the symptoms?Cervin
Please check output from env command , before launching the java program.Biysk
B
4

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?

Biysk answered 13/4, 2012 at 11:48 Comment(1)
Thanks Jayan, I have tried with second command and it works as charm...thanks again..Leilaleilah
P
1

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
Political answered 13/4, 2012 at 11:52 Comment(4)
Pedantically, in bash, source is the alternative form.Rousseau
How to make it Global? i.e. i can access from tomcat as well.Leilaleilah
@AnandSoni I don't think it can be done once Tomcat (or any other program) has started (someone please correct me if I'm wrong). I think you're on Ubuntu, take a look at help.ubuntu.com/community/…Political
@lum. Thanks for replay but have done with writing that export statements in /etc/init.d/tomcat6 at top and restarted the tomcat server by /etc/init.d/tomcat6 restart. So, now it that env. variable will be accessed by web app.Leilaleilah

© 2022 - 2024 — McMap. All rights reserved.