0

I have jar file in some location.(/test/lib/myproject.jar).

In that jar file, I have .sh file (/org/com/api/demo.sh).

Now I want to execute that demo.sh file. How can I execute that file in Linux/Unix?

tripleee
  • 175,061
  • 34
  • 275
  • 318
user2636874
  • 889
  • 4
  • 15
  • 36
  • Either extract sh file from jar or use https://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code – Pacifist Sep 24 '19 at 07:55
  • In case you didn't know: You can use `unzip` to extract data from a .jar file. – Bodo Sep 25 '19 at 16:52
  • If you're executing that script from Java within that jar, you'll have to extract via Class.getResourceAsStream() and either save, or pipe directly to a running shell process – Brian Agnew Dec 31 '19 at 10:14

1 Answers1

1

You can use unzip to extract the file, and pipe it to sh to run it.

unzip -p /test/lib/myproject.jar org/com/api/demo.sh |
sh

Notice how zip files generally cannot contain absolute paths. The first argument to unzip is the archive and the remaining arguments name the archive members to extract; the -p option says to extract to standard output.

As a special case, if you need to execute the code in the context of the current shell (i.e. effectively source it) this is one of the rare cases where wrapping a command in $(...) makes sense. (Many beginners like to try to put this in all kinds of weird places.)

$(unzip -p /test/lib/myproject.jar org/com/api/demo.sh)

You should prefer the first option unless you specifically know that you need the second, and understand the difference. Also, as usual, you should only execute code you trust, and, ideally, have vetted.

If you need to run the code more than once, save it to a file and mark it as executable.

unzip -p /test/lib/myproject.jar org/com/api/demo.sh >demo
chmod +x ./demo

and then to run it

./demo
tripleee
  • 175,061
  • 34
  • 275
  • 318