irshad.ahmad irshad.ahmad - 17 days ago 5
Bash Question

Run .sh File in Java Code on Linux Machine

My Task:
1 - Read an Excel File, parse it and save the data in txt file.
2 - Read that txt file and pass it to a batch.sh file. This batch.sh file do one thing, it picks the data from the above mentioned txt file and save it in a database's table.

When I run the batch.sh file from the terminal(and give it the txt file), it works fine. It inserts the records in the database just as i want.

Problem is, when I want to do the same with the java code, the batch.sh file does not work. And also, no exception is thrown.

Some Explanation: I am using Java 7, Oracle, SQL-Loader, Linux.

Additional Information: If I rename the batch.sh file to batch.bat file and run it in Windows environment, it works perfectly fine. the batch.sh file also works fine if it is executed from the terminal. The only problem is, its not working from java code.

I am listing the java code snippet, batch.sh file and the control.txt file for the following task.

Java Code:

try{
String target = new String("/path/to/batchFile/batch.sh");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(target);
proc.waitFor();
}catch(Exception e){
LOG.error("Exception Occured with Message : "+e.getMessage());
}


Batch.sh:

sqlldr username/password@sid control='/path/to/batchFile/control.txt' log='/path/to/batchFile/Results.log' bad='/path/to/batchFile/BadFile.bad' ERRORS=5000


control.txt:

options ( skip=1 )
load data
infile '/path/to/batchFile/TxtFileData.txt'
truncate into table TABLE_NAME
fields terminated by ","

(
column_name "replace(:column_name,'-','')"
)


P.S: I have read many post regarding the same issue, and tried every solution, but non is working. The current example of java code is taken from another StackOverFlow thread.

Any help will be highly appreciated.

Answer

You'd want runtime.getRuntime.exec(new String[]{"/bin/bash", "-c", "/path/to/script.txt"}) See here: How to execute command with parameters?

Comments