Reputation: 147
I'm writing a shell script to launch several jars in a directory simultaneously. The issue I'm having is getting these to launch as background processes.
All I've been able to do is get the first process to launch, then hang indefinitely. What's strange is that the commands being generated and executed behave as expected when executed explicitly (copy/paste into a shell or create and execute them in a file). This isn't doing anything crazy (I think?). The intent is to get a list of jars in a local directory and launch them as background processes.
Here's the relevant piece that I'm having issues with:
jars=(`ls ${appDirectory}/*jar`)
for j in ${jars[@]}; do `java -jar ${j} 2>&1 > /dev/null &`; done;
Any ideas on what the issue might be? Am I stuck on something with pipes? Is there some black magic I need to be performing to launch background processes from within a shell? Any help is much appreciated. Thanks!
Upvotes: 0
Views: 53
Reputation: 125788
dtmilano has already given a solution to the problem; I'd like to explain why the problem was happening. The root cause was the backquotes in this part of the command:
`java -jar ${j} 2>&1 > /dev/null &`
What backquotes do in the shell is capture the output of the enclosed command, and use it as part of a new command (or in this case an entire command). Thus, it fires off java -jar ${j} 2>&1 > /dev/null
in the background but tries to capture its output. Contrary to what you might think, 2>&1 > /dev/null
does not send both stderr and stdout to /dev/null; it redirects the command's stdout to /dev/null, but the command's stderr gets sent to the outer level's stdout instead. Thus the backquote expression winds up capturing java's stderr. And that means it has to wait until the java instance exits to make sure it's got everything.... even though java is in the background.
Upvotes: 0
Reputation: 69198
I guess what you mean is
for j in ${appDirectory}/*.jar;
do
java -jar ${j} 2>&1 > /dev/null &
done
considering you don't have spaces in filenames.
Upvotes: 2