Search code examples
bashloopsbackground-process

How to continue the script execution after a background process ending?


Good morning

I have this variable

NODES="lep1mk17 lep1mk18 lep1mk19"

And I am executing this loop (I want to work with parallel processes)

56 for i in $NODES
57 do
58        java -jar jmxterm-1.0.1-uber.jar --url <url:port> -i $LOGDIR/$i > $LOGDIR/$i.out &
59        pid-$i=$!
60 done

In this case I will have 3 processes in background.

To know when they finish, I use the variable pid-$i

At this point I want to stop my script until the background processes ending, so I do:

62 for i in $NODES
63 do
64        wait $(pid-$i)
65 done

When I execute the script I got some errors:

./countMessagesTopicV4.sh: line 59: pid-lep1mk17=30491: command not found
./countMessagesTopicV4.sh: line 59: pid-lep1mk18=30493: command not found
./countMessagesTopicV4.sh: line 59: pid-lep1mk19=30495: command not found
./countMessagesTopicV4.sh: line 64: pid-lep1mk17: command not found
./countMessagesTopicV4.sh: line 64: pid-lep1mk18: command not found
./countMessagesTopicV4.sh: line 64: pid-lep1mk19: command not found
emedina@goku:~/script/kafka$ 

Can someone help me to find my error ?


Solution

  • Variable names have to be literal, you can't just use an expression as a variable name like you're doing. (Also variable names can't have - in them, but that's a second problem)

    bash has associative array variables: you want

    59: pid[$i]=$!
    
    ...
    
    64: wait ${pid[$i]}