从Java执行source命令 [英] Execute source command from Java

查看:675
本文介绍了从Java执行source命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本文件,我在shell中使用source命令调用它并设置了许多环境变量。然后我可以使用环境变量设置的所有工具。

I am having a bash script file which I am calling using the source command in a shell and is setting a number of environment variables. Then I can use all the tools the environment variables are setting.

现在我想在Java中使用以下方法:

Now I want to do the same in Java by the use of:

static Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();

我知道source是一个内部命令,我不能用Java调用它。

I know that source is an internal command and I can not call it from Java.

有没有其他方法可以在java中设置该文件中的环境变量,以便以后能够在我的代码中使用它们来调用其他命令?

Is there any other way to set the enviroment variable in that file from java in order to be able to use them in my code later for calling other commands?

提前谢谢!

推荐答案

Process pr = new ProcessBuilder("/bin/bash", "-c", ". env.sh; " + command).start();

尝试这样的方法,你可以在同一个shell进程中获取脚本并执行后续命令。每次要执行命令时,都可以有效地获取脚本。

Try something like this, where you both source the script and execute a subsequent command in the same shell process. Effectively you source the script every time you want to execute a command.

这篇关于从Java执行source命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆