Running shell scripts
We generally collect a set of commands used in performing an operation in a file, called a shell script in the Unix world and a batch file in Windows. The commands present in these files are executed sequentially, with the exceptions being when you have conditional blocks or loops in the scripts.Â
These shell scripts are evaluated by the shell in which they get executed. Different types of shells available are bash
, csh
, ksh
, and so on. The bash
shell is the most commonly used shell.
In this recipe, we will write a simple shell script and then invoke the same from the Java code using the ProcessBuilder
and Process
objects.
Getting ready
First, let's write our shell script. This script does the following:
- Prints the value of the environment variable,Â
MY_VARIABLE
- Executes the
tree
command - Executes the
iostat
command
Let's create a shell script file by the name, script.sh
, with the following commands in it:
echo $MY_VARIABLE;
echo "Running tree command";
tree;
echo "Running iostat...