I am executing the shell script using below method in java
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);
}
}
The jj.sh file contains below value
#!/bin/sh
key=$1
value=`$2`
echo $value
When I execute jj.sh using key and value directly, it give me the correct value, that is, the name of file.
However with java it is giving me the result as ls -1 result (Means java is ignoring the command after '|'). When I pass the key values delimited with tilde sign ` then it simply displays the full key value i.e. ls -1|tail -1
How to execute the full command using java
jj.shwhen you do it directly?runtime.exec()toprocess.start(). Also, neither is a shell; you should invoke the shell and pass the script as an argument to it.ifblock. The variables I'd allow are all strings. But then, you wrotels-1|tail-1without spaces and that will never fly. But then, your shell script wouldn't actually work with a pipe. You're probably running it asjj.sh key ls -1| tail -1, which actually runsjj.sh key ls -1then passes the output totail -1.