java中执行shell脚本

明确场景

  • 在项目中需要执行shell脚本或者shell命令。

具体而言:

  1. 需要通过一个文件夹路径,获取路径下所有git库路径。
    而我本身已经有了这个shell脚本如下:
#!/bin/bash  
  
path=${1}  
cd $path  
for git_path in `find . -name ".git" | awk -F . '{print $2}'`  
do  
  dir=$path${git_path}  
  dir=${dir%?}  
  echo "${dir}"  
done
  1. 将这一脚本集成到java项目中。
  2. 执行shell脚本
  3. 获得终端输出的结果

代码

  1. 首先,仍旧是按照TDD的思想,写好测试。
@Test  
public void should_get_repo_list_from_dir_string() throws IOException {  
    String addr = "/Users/code";  
 	List<String> repoList = getRepoListByDir(addr);  
	assertEquals("/Users/code", repoList.get(0));  //已知该项目下的第一个代码库路径
}  
  
private List<String> getRepoListByDir(String addr) throws IOException {  
    String commandType = "sh";  
	String param1 = "src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh";  
	String param2 = addr;  
	List<String> result = execAndReturn(commandType, param1, param2);  
	return result;  
}
  1. 再编写代码通过测试:
    public static List<String> execAndReturn(String commandType, String param1, String param2) throws IOException {  
        String[] commands = {commandType, param1, param2};  
        Runtime rt = Runtime.getRuntime();  
        Process proc = rt.exec(commands);  
        List<String> result = new ArrayList<>();  
  
		BufferedReader print = new BufferedReader(new  
		InputStreamReader(proc.getInputStream()));  
		  
		BufferedReader stdError = new BufferedReader(new  
		InputStreamReader(proc.getErrorStream()));  
		  
		// Read the output from the command  
		String s = null;  
		while ((s = print.readLine()) != null) {  
            result.add(s);  
	    }  
  
		// Read any errors from the attempted command  
		 while ((s = stdError.readLine()) != null) {  
		            throw new RuntimeException("shell comand exec failed: " + s);  
		 }  
		        return result;  
}

总结

命令本身与参数一定要分离

在终端执行shell命令如下:
sh src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh /Users/code

  • 在java中使用执行过程中需要进行拆分成三个字符串:

“sh”
“src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh”
“/Users/code”

String[] commands = {commandType, param1, param2};  
Process proc = Runtime.getRuntime().exec(commands);

对于不同参数个数的shell命令可以通过变长参数处理。

    public static List<String> execAndReturn(String ... param) throws IOException {
        String[] commands = param;
        ...
    }
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值