Sunday 16 June 2019

Java11: #!: Shebang files: Write Executable scripts in Java


Since java launcher launch the source code file directly using java launcher, you can use #! (Shebang line) to execute the java file as script.

Create a file hello like below.

hello
#!/usr/bin/java --source 11

public class Hello{
      public static void main(String args[]){
            System.out.println("Welcome to Java11 Programming");
      }
}


Give executable permission to hello file and run.
$chmod +x hello
$
$./hello
Welcome to Java11 Programming

First line in shebang file looks like below.
#!/path/to/java --source version

Any arguments that you pass to shebang file are passed as command line arguments to the application.


factorial
#!/usr/bin/java --source 11

public class Factorial{

      public static int factorial(int num){
            int result = 1;

            for(int i = 2; i <= num; i++){
                  result *= i;
            }

            return result;
      }

      public static void main(String args[]){

            if(args.length != 1){
                  System.out.println("Please enter valid input");
                  System.out.println("./factorial <num>");
                  return;
            }

            int num = Integer.parseInt(args[0]);
            int result = factorial(num);

            System.out.println("Factorial of " + num + " is " + result);
      }
}


$chmod +x factorial
$
$./factorial 
Please enter valid input
./factorial <num>
$
$./factorial 5
Factorial of 5 is 120
$

Shebang file can also be launched by java launcher.

java -Dtrace=true --source 10 factorial 3

$java --source 11 factorial 3
Factorial of 3 is 6

While executing the script file from java launcher, you can remove the shebang line.


factorial
public class Factorial{

      public static int factorial(int num){
            int result = 1;

            for(int i = 2; i <= num; i++){
                  result *= i;
            }

            return result;
      }

      public static void main(String args[]){

            if(args.length != 1){
                  System.out.println("Please enter valid input");
                  System.out.println("./factorial <num>");
                  return;
            }

            int num = Integer.parseInt(args[0]);
            int result = factorial(num);

            System.out.println("Factorial of " + num + " is " + result);
      }
}

$java --source 11 factorial 3
Factorial of 3 is 6

Reference





Previous                                                 Next                                                 Home

No comments:

Post a Comment