shell脚本语言 Java调用shell脚本_执行脚本文件命令

11/27 21:12:41 来源网站:辅助卡盟网

注意:如果把命令放到一个String[]中时,必须把命令中每个部分作为一个元素存在String[]中,或者是把命令按照空格符分割得到的String[]。

String[] cmd = {"tar", "-cf", tarName, fileName};		//right
String[] cmd = {"tar -cf", tarName, fileName};			//error

为了说明dir参数的作用,我特地把该Java程序和要打包的目录hive/放在不同的目录:

/root/workspace/eclipse/Test/src/edu/wzm/CallShell.java
/root/experiment/hive

如果我不设置dir或设dir为null,那么fileName不得不是相对路径,最好是绝对路径:

call.callCMD("/root/experiment/hive.tar", "/root/experiment/hive", null);
// OR

linux shell脚本语言_shell脚本语言_常用shell脚本语言

如果我设置了dir指向了hive所在的父目录就好办多了:

call.callCMD("hive.tar", "hive", "/root/experiment/");

3.调用Shell脚本

Java调用Shell命令和调用Shell脚本的操作一模一样。我这里介绍另外几个方面:

给脚本传递参数;捕获调用的输出结果;envp的使用。

给脚本传递参数,这个操作很简单,无非是把参数加到调用命令后面组成String,或String[]。

捕获调用输出信息,前面也提到过用Process.getInputStream()。不过,建议最好对输入流进行缓冲:

BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

另外,envp是一个String[]shell脚本语言,并且String[]中的每一个元素的形式是:name=value。如:我的Linux系统中没有以下环境变量,但是我把它们写在Java代码中,作为envp:

val=2
call=Bash Shell

我要调用的Shell脚本是:/root/experiment/test.sh。

#!/usr/bin/env bash
args=1
if [ $# -eq 1 ];then
	args=$1
	echo "The argument is: $args"
fi

常用shell脚本语言_linux shell脚本语言_shell脚本语言

Java调用代码是:

private void callScript(String script, String args, String... workspace){
	try {
		String cmd = "sh " + script + " " + args;
//        	String[] cmd = {"sh", script, "4"};
		File dir = null;
		if(workspace[0] != null){
			dir = new File(workspace[0]);
			System.out.println(workspace[0]);
		}
		String[] evnp = {"val=2", "call=Bash Shell"};
		process = Runtime.getRuntime().exec(cmd, evnp, dir);
//            process = Runtime.getRuntime().exec(cmd);

shell脚本语言_常用shell脚本语言_linux shell脚本语言

输出:

/root/experiment/
The argument is: 4
This is a Bash Shell
Cost Time: 24

来源:【九爱网址导航www.fuzhukm.com】 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    暂无相关资讯
shell脚本语言 Java调用shell脚本_执行脚本文件命令