How to run shell script from a Java program

Vishal Racharla
2 min readNov 30, 2022

--

To achieve this we will be using apache-commons-exec library

We will se how this works with a very simple example

  1. 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

hello.sh

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 :

Response

--

--