[英]Set environment variable in shell script/access in Java program
I want to set environment using shell scrip in Ubuntu 10.04 and want to access in java program. 我想在Ubuntu 10.04中使用Shell Scrip设置环境,并想在Java程序中访问。 I have wrote shell script like this:
我写了这样的shell脚本:
#! /bin/sh
export JAVA=/home/ubuntu
echo "Variable $JAVA"
and my java program is : 而我的java程序是:
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. 当我在不使用Shell脚本的情况下执行此命令时,它运行良好,但是在Shell脚本中却无法运行。
How are you sourcing the script? 您如何采购脚本?
$./myscript.sh
or 要么
$source ./myscript.sh
The second will set the environment variable to current shell. 第二个将环境变量设置为当前shell。 The java program looks ok.
Java程序看起来还可以。
EDIT: based on the comment 编辑:基于评论
It was a problem related to subshell. 这是与subshell有关的问题。 A quick read is
快速阅读是
What is the difference between executing a bash script and sourcing a bash script? 执行bash脚本和采购bash脚本有什么区别?
What are you trying to do exactly? 您到底想做什么?
Running JAVA=/home/ubuntu java SystemEnv
works fine (ie it outputs "/home/ubuntu") 运行
JAVA=/home/ubuntu java SystemEnv
可以正常工作(即输出“ / 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.