Compile and Build with Java Single Command Line (Linux)
Is there a way to set up an alias so that I can enter a command followed by an argument on the same line?
For example, instead of
javac Program.java && java Program
I could go
newcommand Program.java //or "newcommand Program", whichever is easier
which will execute the same commands as the line above.
source to share
Adding an answer to enrico.bacis, I personally don't like when Program.class files clutter my workspace if I am just testing a program, so I would do
jcar() { javac $1.java && java $1 && rm $1.class}
Also, I was comfortable with catching ctrl-c
, so even if I end the program halfway through, it still deletes.class
jcar() {
trap "rm $1.class" SIGINT SIGTERM
javac $1.java
java $1
rm $1.class
}
source to share
I like to pass the fully qualified name Program.java as an input parameter, which makes it easy to autocomplete.
Here's an edited version of a notcompletelyrational script that expects commands like jcar Program.java
, not jcar Program
:
jcar() {
f=$1
f2=${f%.*}
trap "rm $f2.class" SIGINT SIGTERM
javac $1
java $f2
rm $f2.class
}
source to share
I was about to answer you by providing a portion of the Makefile, but that would not be general enough. Whenever you want to compile a more complex program (say 2 files), you also need to compile the second one. It might be in a package, in which case what you are asking for no longer works. It's the same if you have to handle libraries.
For all these reasons, I strongly recommend that you choose a useful tool of your choice make
, scons
, ant
and point to it maven
. I find a later way to compromise small projects. But ant
- my best candidate for Java programs. In the end, you can simply ant run
, which will run your program and recompile it if necessary. See hello world with ant.
source to share
Adding to enrico.bacis' and notcompletelyrational answer, how to run it under a package and clean up the compiled package files:
jcar() {
javac -d . $1.java && java ${PWD##*/}.$1 && rm -rf ${PWD##*/}/
}
By the way, this function should be added to ~ / .bash_profile for Mac OS and ~ / .bashrc for Linux respectively.
To run it:
jcar ProgramName
source to share