我正在使用以下方法在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);
}
}
jj.sh文件包含以下值:
#!/bin/sh
key=$1
value=`$2`
echo $value
当我直接使用密钥和值执行jj.sh时,它会给出正确的值,即文件名。 但是使用Java时,它将结果作为ls -1结果(这意味着Java忽略了“|”之后的命令)。当我传递用波浪线“~”分隔的密钥值时,它只显示完整的键值,即
ls -1 | tail -1
。如何使用Java执行完整命令?
jj.sh
时,该如何操作? - that other guyruntime.exec()
转换为process.start()
。而且,这两者都不是shell; 你应该调用shell并将脚本作为参数传递给它。 - Stephen P