可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
An alias
is not made to accept parameters, define a function like this:
jcar() { javac $1.java && java $1 ; }
Then use it:
jcar Program
(jcar
was intended as an acronym for java-compile-and-run)
回答2:
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
jcar() {
trap "rm $1.class" SIGINT SIGTERM
javac $1.java
java $1
rm $1.class
}
回答3:
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 than jcar Program
:
jcar() {
f=$1
f2=${f%.*}
trap "rm $f2.class" SIGINT SIGTERM
javac $1
java $f2
rm $f2.class
}
回答4:
Since Java 11 you can use a single command
java example.java
https://openjdk.java.net/jeps/330
Linked: How to compile and run in single command in java
回答5:
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 it maven
. I find the later way to complex for small projects. But ant
is my best candidate for java programs. In the end, you can just ant run
which will run your program and recompile it if needed. Have a look on the hello world tutorial with ant.
回答6:
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:
jcar ProgramName
回答7:
My favorite solution looks like this:
function jcar { javac ${1%.*}.java && java ${1%.*}; }
It can handle various inputs, such as
jcar myfile
jcar myfile.
jcar myfile.java
jcar myfile.class
It lets you use Tab more quickly :)