-1

I have a java program which runs on Linux and attempts to call one shell script. This shell script tries to copy a local directory to another server. The way to call the script is :

bash copy_logs.sh "TestResults/07232015042652"

When i call this from linux terminal, the directory gets copied to remote server successfully. Now i want to execute this from Java program. My code snippet is as follows :

Sting direc = "07232015042652"
p = Runtime.getRuntime().exec("bash copy_logs.sh \"TestResults/"+direc+"\"");

When i run this, though i do not get any error or exception but the file never gets copied.

Contents of copy_logs.sh is as follows :

scp -r $TS [email protected]:/home/apacheweb/html/Weekly_Status/prov_check/
if [ $? -eq 0 ]
then
        echo "File copied successfully"
else
echo "Failed to copy"

I tried to print the result of execution by

InputStream is = p.getInputStream();
    StringBuilder sb = new StringBuilder();

    int i=0;
    try {
        while ((i=is.read())!=-1){
            sb.append((char)i);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(sb);

And i get the output : Failed to copy . Just wondering what can be root cause of this???

5
  • 1
    I'd consider using ProcessBuilder instead of Runtime.exec as it will allow to specify each part of the command as a separate String which will help with quoting parameters (as you don't need to) and parameters with spaces. May not fix the immediate problem, but will help resolve/eliminate other potential issues Commented Jul 30, 2015 at 0:31
  • as @MadProgrammer said, using ProcessBuilder will also make it easier to debug Commented Jul 30, 2015 at 0:42
  • Thanks for suggestion. I already tried ProcessBuilder but it didn't helped :( Commented Jul 30, 2015 at 1:55
  • Didn't say it would solve the problem, but it will help you solve it in the long run, as if used correctly, it will remove much of the ambiguity that you get from Runtime.exec Commented Jul 30, 2015 at 2:15
  • Chillax madProgrammer, i am just updating you that it didn't worked, not blaming you Sir.. Commented Jul 30, 2015 at 14:07

1 Answer 1

0

Got it working by :

 ProcessBuilder pb = new ProcessBuilder("bash", "-c", "/bin/bash copy_logs.sh \"TestResults/"+directoryName+"\"");
 Process shell = pb.start();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.