Java 操作Shell脚本

1、新建一个springboot项目demo。

2、编写controller、service、serviceImpl、printTest2.sh脚本,如下文的代码所示。

3、把项目打成jar包。

4、把jar包放到linux 系统中。

5、执行jar包  : java -jar demo-0.0.1-SNAPSHOT.jar

 

Process类:

java.lang.Process

 

shell 命令参考:

https://www.runoob.com/linux/linux-shell-printf.html

 

Controller

import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.ShellService;

@RestController
public class ShellController {

    @Autowired
    ShellService shellService;
    
    @GetMapping("/shell/test")
    public String hello(){
        return "Hello , This is you first SpringBoot Web Project !";
    }
    
    @GetMapping("/shell")
    public String shell(String scriptPara){
        //call.callScript("test.sh", "4", "D://log");
        String script = "/具体目录/demo/test.sh";
        String args = "";
        String workspace = "/具体目录/app/demo";
        if(null != scriptPara){
            script = scriptPara;
        }
        try {
            shellService.callScript(script, args, workspace);
        } catch (IOException e) {
            return "失败 "+e.getLocalizedMessage();
        }
        return "Hello , This is you first SpringBoot Web Project !";
    }
}
 

ShellService

import java.io.IOException;

public interface ShellService {

    public void callCMD(String tarName, String fileName, String... workspace) throws IOException,InterruptedException;
    
    public void callScript(String script, String args, String... workspace)  throws IOException;
}

ShellServiceImpl

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.stereotype.Service;

import com.example.demo.service.ShellService;

@Service("shellService")
public class ShellServiceImpl implements ShellService{

    private Process process = null;
    
    @Override
    public void callCMD(String tarName, String fileName, String... workspace) throws IOException, InterruptedException {
        String cmd = "tar -cf" + tarName + " " + fileName;
//                String[] cmd = {"tar", "-cf", tarName, fileName};
        File dir = null;
        if(workspace[0] != null){
            dir = new File(workspace[0]);
            System.out.println(workspace[0]);
        }
        process = Runtime.getRuntime().exec(cmd, null, dir);
//              process = Runtime.getRuntime().exec(cmd);
        int status = process.waitFor();
        if(status != 0){
            System.err.println("Failed to call shell's command and the return status's is: " + status);
        }
    }

    @Override
    public void callScript(String script, String args, String... workspace) throws IOException {
        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);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        input.close();
    }
    
}

 

测试:

1、访问

http://ip:port/shell?scriptPara=具体目录/demo/printTest2.sh

2、结果

 

printTest2.sh:

#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com
 
# format-string为双引号
printf "%d %s\n" 1 "abc"

# 单引号与双引号效果一样
printf '%d %s\n' 1 "abc"

# 没有引号也可以输出
printf %s abcdef

# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用
printf %s abc def

printf "%s\n" abc def

printf "%s %s %s\n" a b c d e f g h i j

# 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
printf "%s and %d \n"

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中执行Shell脚本可以使用`Runtime`类或`ProcessBuilder`类。下面是使用`Runtime`类执行Shell脚本的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 String command = "sh /path/to/script.sh"; Process process = Runtime.getRuntime().exec(command); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 上述代码中,`/path/to/script.sh`是你要执行的Shell脚本的路径。你可以将实际的Shell脚本路径替换到代码中。 使用`ProcessBuilder`类执行Shell脚本的示例代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 ProcessBuilder processBuilder = new ProcessBuilder("sh", "/path/to/script.sh"); Process process = processBuilder.start(); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 同样,你需要将实际的Shell脚本路径替换到代码中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值