java获取shell脚本返回值
时间: 2023-06-28 20:12:10 浏览: 76
Java可以通过Process类执行Shell脚本,并通过该类的waitFor()方法获取Shell脚本执行的返回值。
示例代码如下:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellExecute {
public static void main(String[] args) throws IOException, InterruptedException {
String command = "sh /path/to/script.sh";
Process process = Runtime.getRuntime().exec(command);
int exitCode = process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
if (exitCode == 0) {
System.out.println("Shell脚本执行成功!");
} else {
System.out.println("Shell脚本执行失败,返回值:" + exitCode);
}
}
}
```
其中,command变量存储要执行的Shell脚本的命令,process.waitFor()方法会等待脚本执行完成并返回脚本的退出状态码。如果退出状态码为0,则代表脚本执行成功。如果不为0,则代表脚本执行失败,并可以根据具体的状态码进行处理。通过BufferedReader类读取脚本的输出信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)