Compiling and Executing a Java File With a Shell Script

I'm trying to use a shell script to compile and execute a java file. The java classes are using sockets, so there is a client.java file and a server.java file, each with their own shell script. I also want to handle the command line arguments within the shell script, not the java classes. The server script should take a port number and try to start a server on that port, if its unavailable it should exit with a message. The client script should take a host name and a port number and do the same.

I've tried a few variations of the below code with no success. Any tips would be really appreciated, thanks!

#!/bin/bash

javac server.java $@

hostName = $1
portNumber = $2

I think you will have to handle the arguments in both - the shell script and the Java program.

  • You pass the arguments from the shell script to the Java class.
  • Your Java class accepts and uses those arguments to open the socket, talk to the client/server etc.

That's incorrect.
Assuming you have the Java program: "Server.java" that has all the Java code to accept, parse and use the (port number) argument, you will have to do the following (note the commands in red):

(a) Compile the Java program file "Server.java" into a Java class first. Use this command:

javac Server.java

The "javac" command, if successful, will create a new file called "Server.class" in the same directory as the "Server.java" file.

(b) Run the Java class file "Server.class", passing the argument to it. Use the following command:

java Server 4444

Do the same thing for the Java client program, say, "Client.java".
From a Bash shell script, it would look like this:

#!/bin/bash
host_name="myserver.example.com"
port_number=4444
  
# First, compile the Java programs into Java classes
javac Server.java
javac Client.java
  
# Now pass the arguments to the Java classes
java Server ${port_number}
java Client ${host_name} ${port_number}

You then invoke your Bash script without any arguments because the host and port values are hard coded.

Otherwise, if you want to pass those values to the Bash script, which will, in turn, pass them to the Java classes, then:

#!/bin/bash
host_name=$1
port_number=$2
  
# First, compile the Java programs into Java classes
javac Server.java
javac Client.java
  
# Now pass the arguments to the Java classes
java Server ${port_number}
java Client ${host_name} ${port_number}

And you then invoke your Bash script like so, assuming you have given execute privilege on the script to yourself:

./client_server.sh myserver.example.com 4444

==========
Sorry, I didn't realize you mentioned you had a shell script for each of the Java programs.
If you understood the concepts in the post above, then you shouldn't have any problem using them in your two scripts.
If you get stuck, then post your question with a code snippet and the error you encounter.