45

Is it possible to use threads in bash scripts. I have a driver class in java that i'm trying to run multiple instances of at the same time. The only way i know to do this is make threads in bash, but i'm not sure if thats even possible. Any help would be appreciated

Alexander Pogrebnyak
  • 43,823
  • 10
  • 101
  • 118
auwall
  • 713
  • 1
  • 8
  • 9

3 Answers3

53

Bash doesn't support threading per se, but you could launch multiple java processes in the background, like:

java myprog &
java myprog &
java myprog &

Anything more than that you might look into Python or Ruby, which have thread management utilities, you could wait for each one to finish and collect output/exit status, etc.

Edit: Borrowing the suggestion from @CédricJulien to use wait, here's a more thorough example. Given this MyProg.java program:

public class MyProg {
    public static void main(String[] args) {
        System.exit(Integer.parseInt(args[0]));
    }
}

you could write the following bash-threads.sh script to launch multiple instances of it in parallel:

#!/bin/bash
set -o errexit

java MyProg 1 &
pid1=$!
java MyProg 0 &
pid2=$!
java MyProg 2 &
pid3=$!

wait $pid1 && echo "pid1 exited normally" || echo "pid1 exited abnormally with status $?"
wait $pid2 && echo "pid2 exited normally" || echo "pid2 exited abnormally with status $?"
wait $pid3 && echo "pid3 exited normally" || echo "pid3 exited abnormally with status $?"

Its output is:

pid1 exited abnormally with status 1
pid2 exited normally
pid3 exited abnormally with status 2
Steve Kehlet
  • 5,786
  • 5
  • 36
  • 39
45

You won't be able to launch some "bash threads", but you can launch subprocesses in bash, just using the & after the command, and it will launch it in a background process.

Call a wait after launching your processes to wait for them to be finished.

Try this

first_command &
second_command &

wait
Cédric Julien
  • 74,806
  • 15
  • 120
  • 127
  • 2
    If I could check both of them I would. Both answers were perfect, but his was just before. – auwall May 27 '11 at 19:31
0

Bash >= 4.0 supports the coproc keyword

coproc runs a command as though it was suffixed with & but allows access to it's process ID as well as stdin and stdout.

e.g.

coproc MYJOB myprog <args>

The process id of myprog is now $MYJOB_PID

An array variable $MYJOB then contains file descriptors for the job's stdout in $MYJOB[0] and stdin in $MYJOB[1]

Jason M
  • 3,157
  • 1
  • 20
  • 27