我想在Ubuntu 10.04中使用shell脚本设置环境,并希望在java程序中访问。我写了这样的shell脚本:
#! /bin/sh
export JAVA=/home/ubuntu
echo "Variable $JAVA"
我的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")));
}
}
当我在没有shell脚本的情况下执行此命令时,它运行良好,但在shell脚本中却没有。
答案 0 :(得分:4)
你是如何采购剧本的?
$./myscript.sh
或
$source ./myscript.sh
第二个将环境变量设置为当前shell。 java程序看起来不错。
编辑:根据评论
这是与子shell相关的问题。快速阅读是 What is the difference between executing a bash script and sourcing a bash script?
答案 1 :(得分:1)
你准备做什么?
正常运行JAVA=/home/ubuntu java SystemEnv
(即输出“/ home / ubuntu”)
如果要将环境变量导出到父进程,则必须使用它:
source ./myscript.sh
. ./myscript.sh # Alternative form