Skip to content
Advertisement

How to create a shell script which can create a .java file on executing?

The requirement is to create a shell script that can create a FileName.java file where FileName would be the parameter passed to the script while running the script.

Example:

$ ./shellscript.sh Sample

On executing the above command, a file Sample.java should get created with content:

class Sample{
   public static void main(String[] args){
      for(int i=0;i<10;i++){
      System.out.println("Hello World !!!"); 
   }
}

If sources for learning bash scripting is added in the answer it would be very helpful.

Advertisement

Answer

Here-docs will expand variables, so

NAME=$1
cat << EOF > $NAME.java
class $NAME{
   public static void main(String[] args){
      for(int i=0;i<10;i++){
      System.out.println("Hello World !!!"); 
   }
}
EOF
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement