在最近的工作中,需要用到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之间要有空格
但不要忘记空格!!
 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



转载于:https://blog.51cto.com/gz521/1912304