java 执行shell

/*********************
 * @CLASS:CallShell
 * @DESCRIPTION:在服务器端调用shell执行操作
 * @AUTHOR:yehui
 * @VERSION:v1.0
 * @DATE:2013-4-8 下午3:34:33
 */


public class CallShell {


public static int callShell(String shellString) {


Process process = null;
String[] shell = new String[] { "/bin/sh", "-c", shellString };
int exitValue = 0;
StringBuffer result=new StringBuffer();
try {
process = Runtime.getRuntime().exec(shell, null, null);
exitValue = process.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
result.append(line).append("\r\n");
}
input.close();
// 判断返回数据是否正确
if (result.toString().indexOf("failed") == -1){
exitValue=1;
} else {
exitValue=-1;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return exitValue;
}


/**
* @param args
*/
public static void main(String[] args) {


callShell("/home/svn/proj/D13AL/document/shell/test.sh");
// callShell("sh /home/svn/proj/D13AL/document/0_20_Cob.sh");


}


}


需要执行的shell

#!/bin/sh


#print hello world in the console window


a = "hello world"


echo $a


这个shell 会返回echo $a 所对应的值“hello world”,在




执行这个后,input中会保存有”hello world“!这样的话就可以对返回值进行判断,来得知shell是否已经执行成功!

注意:一定要为shell文件添加所必要的权限


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值