How to run shell script from a Java program
To achieve this we will be using apache-commons-exec library
We will se how this works with a very simple example
- Add required dependencies
implementation group: 'org.apache.commons', name: 'commons-exec', version: '1.3'
2.Now write a very simple shell script which takes one parameter
3.Let’s run this script using the apache-commons-exec library
public static void main(String[] args) throws IOException {
CommandLine commandLine = CommandLine.parse("sh ./hello.sh blogger");
DefaultExecutor defaultExecutor = new DefaultExecutor();
defaultExecutor.execute(commandLine);
}
As per documentation
CommandLine objects help handling command lines specifying processes to execute. The class can be used to a command line by an application
DefaultExecutor is the default class to start a subprocess.
The implementation allows to set a current working directory for the subprocess
a)provide a set of environment variables passed to the subprocess
b)capture the subprocess output of stdout and stderr using an ExecuteStreamHandler
c)kill long-running processes using an ExecuteWatchdog
d)define a set of expected exit values
e)terminate any started processes when the main process is terminating using a ProcessDestroyer
Response :