Is there way to set up an alias in such a way so that I could enter the command, followed by the argument in a single line?
For example, instead of
javac Program.java && java Program
I would be able to go
newcommand Program.java //or "newcommand Program", whichever is easier
which would do the same commands as the line above.
I was going to answer you giving a piece of Makefile, but it would not be generic enough. Whenever you want to compile a more complex program (let's say 2 files), you need to compile the second as well. It might be in a package, in which case what you're asking does not work any longer. Same thing if you have to handle libraries.
For all these reasons, I strongly advise you to choose a building utility of your choice,
make
,scons
,ant
, and let's mention itmaven
. I find the later way to complex for small projects. Butant
is my best candidate for java programs. In the end, you can justant run
which will run your program and recompile it if needed. Have a look on the hello world tutorial with ant.Adding on to enrico.bacis' and notcompletelyrational's answer, how to run it under a package and clean up the package compiled 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:
I like to pass the full Program.java filename as the input parameter, allowing easy autocompletion.
Here's an edited version of notcompletelyrational's script, which expects commands like
jcar Program.java
rather thanjcar Program
:Adding on to enrico.bacis' answer, i personally don't like to have Program.class files cluttering up my workspace if i'm just testing a program, so i'd do
jcar() { javac $1.java && java $1 && rm $1.class}
in addition, i found it helpful to trap
ctrl-c
so that even if i end the program halfway, it still removes the.class
An
alias
is not made to accept parameters, define a function like this:Then use it:
(
jcar
was intended as an acronym for java-compile-and-run)My favorite solution looks like this:
It can handle various inputs, such as
It lets you use Tab more quickly :)