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


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