1

I have implemented a chat server client. I have written the following shell script to dynamically take in the server port number: server.sh

javac -classpath . com/chat/ChatConstants.java

javac -classpath . com/chat/ChatServer.java

echo Enter server port number

read $1

java com.chat.ChatServer $1

This is the java main method I am trying to pass the argument to :

public static void main(String args[]) {
    // The default port number.
    int portNumber = 8888;
    if (args.length < 1) {
        System.out.println("Chat server is up on " + portNumber);
    } else {
        portNumber = Integer.valueOf(args[0]).intValue();
        System.out.println("Chat server is up on " + portNumber);
    }
   }

However, the port number printed is always the default port ie 8888. When I run the java program as follows

java com.chat.ChatServer 2727

The cmd line args are taken properly and server port is set to 2727.

I seem to be doing something wrong in the shell script. I even tried passing the arguments with quotes as follows:

java com.chat.ChatServer "$1"

The command prompt closes promptly.

Please help

jarvis_13
  • 73
  • 1
  • 7
  • Don't name your variable `$1`. That already has a meaning in shell. – Elliott Frisch Aug 19 '18 at 16:36
  • the line read $1 is unnecessary in theory, the $1 refers to the first argument by [default](https://stackoverflow.com/questions/29258603/what-do-0-1-2-mean-in-shell-script/29258644). – m4gic Aug 19 '18 at 16:42

2 Answers2

2

Your script should be:

read PORT
java com.chat.ChatServer $PORT
0

$1 is a special variable which holds the first commandline argument passed to the shell script.

You need to read your input into a different variable.

Edit: Just a sidenote, you can print a prompt without using echo by using read -p "Enter server port number" P.

nom
  • 256
  • 3
  • 16