A Better Shell Script Wrapper for JAR Files
To run a JAR file, usually you would do:
$
java -jar /path/to/jar
It’s a bit long to type, so some people (me included) would wrap it in a shell script:
#!/usr/bin/bash
java -jar /path/to/jar
This way, you only have to type ./run-jar.sh
, or run-jar.sh
if you have the script somewhere in your shell’s PATH
.
A problem with this approach is that you now have two files, the shell script and the JAR file. If you move or delete the JAR file, the script breaks. A better way to do this is to “include” the JAR file directly in the shell script.
First, we’ll change run-jar.sh
’s shebang (#!
) line from #!/usr/bin/bash
to #!/usr/bin/java
. This tells the shell to run the script using java -jar
instead of the usual bash or sh:
$
echo '#!/usr/bin/java -jar' > run-jar.sh
Then, we’ll append the entire JAR file to the script:
$
cat /path/to/jar >> run-jar.sh
Finally, all we have to do is set the script file permission to executable:
$
chmod +x run-jar.sh
This way, everything you need to run the program is in a single file, making it simpler to manage.
Hi 👋. If you like this post, consider sharing it on X or Hacker News . Have a comment or correction? Feel free to email me or reach out on X. You can also subscribe to new articles via RSS.
Continue reading: