Lea*_*ner 2 java linux bash shell
我在java中使用下面的方法执行shell脚本
public static void main(String ar[])
{
//key value are being read from properties file, here I am assigning the sample values directly
key=mine
value="ls-1|tail-1"
String[] cmd = { "jj.sh" , key,value};
Process script_exec = Runtime.getRuntime().exec(cmd);
script_exec.waitFor();
if(script_exec.exitValue() != 0){
System.out.println("Error while executing script");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(script_exec.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
jj.sh文件包含以下值
#!/bin/sh
key=$1
value=`$2`
echo $value
Run Code Online (Sandbox Code Playgroud)
当我直接使用key和value执行jj.sh时,它会给我正确的值,即文件名.但是对于java,它给我结果为ls -1 result(表示java忽略'|'之后的命令).当我传递用波形符号`分隔的键值时,它只显示完整的键值即ls -1|tail -1
如何使用java执行完整命令
这不起作用的主要原因`$2`是`ls -1 | tail -1`,即使$2设置为该字符串,也不一样.
如果脚本接受带有要执行的命令的文字字符串,则可以使用eval这样做.
我创建了一个完整的例子.在您尝试将其中任何一个应用到您自己的代码之前,请复制粘贴并验证它是否有效.这是Test.java:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String[] command = { "./myscript", "key", "ls -t | tail -n 1" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
而且myscript:
#!/bin/bash
key="$1"
value=$(eval "$2")
echo "The command $2 evaluated to: $value"
Run Code Online (Sandbox Code Playgroud)
以下是我们如何myscript单独运行:
$ ls -t | tail -n 1
Templates
$ ./myscript foo 'ls -t | tail -n 1'
The command ls -t | tail -n 1 evaluated to: Templates
Run Code Online (Sandbox Code Playgroud)
这是运行Java代码的结果:
$ javac Test.java && java Test
Script output: The command ls -t | tail -n 1 evaluated to: Templates
Run Code Online (Sandbox Code Playgroud)