java调用shell脚本且传递参数

在最近的工作中,需要用到Java要调用shell脚本的情况。总结如下:


    @RequestMapping("/changePermission")

public String changePermission(){

String returnCode = "";

try {

Process process = Runtime.getRuntime().exec("chmod 755 /tmp/upgrade.sh");

process.waitFor();

                // test2.sh是要执行的shell文件,param1参数值,test2.sh和param1之间要有空格

                // 多个参数可以在param1后面继续增加,但不要忘记空格!!

process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/tmp/test2.sh param1"});

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

String line = null;

StringBuffer sb = new StringBuffer("");

while((line=br.readLine()) != null){

sb.append(line);

}

br.close();

System.out.println(sb.toString());

returnCode = process.waitFor()+"";

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

return returnCode;

}

shell脚本test2.sh代码如下:

#!/bin/bash

name=$1

echo $name

mv /usr/local/upgrade.sh /usr/local/${name}.sh


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章