Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a "macro" command to run a program

I have a Main.java file and I want to run the program passing it test.txt

I know in command line I can write javac Main.java

After compiling I can write java Main test.txt and this will accomplish running the file and passing test.txt

If I wanted instead to be able to just write main test.txt and have that trigger my Main.class file to run is that possible and if so how?

like image 313
brucebomber Avatar asked Nov 04 '22 15:11

brucebomber


2 Answers

(Edit: Based on your comment, let me expand to add a couple more situations)

If your goal is to have someone else run your program who does not have Java installed, and you do not wish to have them install a Java runtime environment before running your app, what you need is a program that converts the .class or .jar files into a native executable for the platform you are using. How to do this has been covered in other questions, eg: Compiling a java program into an executable . Essentially, you use a program like JCG (GNU Compiler for Java) or Excelsior JET (a commercial product) to expand the byte code into full native code with a mini-JRE built in.

If your goal is to save typing, there are a number of strategies. Others have suggested alias commands, which work well on linux.

A slightly more portable option that you could ship with your program would be a shell script. Granted, shell scripts only run on linux or other OS's with shell script interpreters installed.

Here is an example shell script. You paste this into a text editor and save it as main with no extensio. The $1 passes the parameter argument fyi.

#!/bin/sh
java Main $1

presuming you name your shell script just "main" with no extension, you could call main test.txt to execute your program now.

If you are on Windows, you might want to create a windows shortcut, and point the shortcut to "java Main test.text", using the full paths if necessary (if the paths are not already set). Of course, this does not make the parameter easy to change every time you run it, you would have to edit the shortcut.

like image 175
Jessica Brown Avatar answered Nov 09 '22 23:11

Jessica Brown


add an alias e.g. under a mac edit your .bash_profile with the following line

alias main='java main'

don't forget to open a new console to see your alias working

like image 23
luko Avatar answered Nov 10 '22 01:11

luko