Starting with Java11, you can run java
directly with source files as well, e.g. java MyClass.java
So, in theory, you can do something like this (in bash):
echo 'public class TmpClass{ public static void main(String[] args){System.out.println("Hello World");}}' > /tmp/TmpClass.java && java /tmp/TmpClass.java
Not elegant in any way, and probably not much useful either, but i guess it can be done.
To make it a bit less verbose on the command line, you can create a simple bash script runjava.sh
and invoke it as
$ runjava.sh 'System.out.println("Hello World");'
Hello World
runjava.sh:
#!/bin/bash
# inject given line inside the main method of a temp class
read -d '' tmpclass <<EOF
public class TmpClass{
public static void main(String[] args) throws Exception {
$@
}
}
EOF
tmpfile=/tmp/TmpClass.java
# write generated source code to a temporary file
echo $tmpclass > $tmpfile
# execute the source file directly (requires Java11+)
java $tmpfile
# delete the temporary file
rm $tmpfile
jshell would probably be a better fit, but since you asked specifically for a non-jshell solution..