I want to have a Java tool that accepts optional parameters from bash itself or from a bash script. I have the following class to read in optional command line arguments:
public class Params {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no args given.");
System.exit(0);
} else {
for (String arg : args) {
System.out.println(arg);
}
}
}
}
When I run it from bash without arguments, I get “no args given”. Fine. When I enter any number of optional arguments I get them as output. Fine too. But when I run the command from a bash script, I get the message in both cases – also in the case that I give an optional parameter.
This is my bash script:
#!/usr/bin/env sh
java -cp . src/main/java/com/me/tool/Params.java
When I change the script to:
#!/usr/bin/env sh
java -cp . src/main/java/com/me/tool/Params.java "$1" "$2" "$3" "$4"
without a parameter then I get four empty lines for the four options that I did not hand over. I want to see only the hint message instead. How can I change the bash script to optionally accept any number of arguments and pass it to the class so that I get the error message if no arguments were given?