0

I wrote the following for loop (spread over multiple lines here for better readability):

for F in CLEAN_READS/*_1.fa; do
  R=${F%_*}_2.fa; BASE=${F##*/};
  SAMPLE=${BASE%_*};
  metascript assembly -1 $F -2 $R -o folder_${BASE%_*} &
done

When I run the loop all scripts are started in parallel. How can I change the loop to start the scripts in sequential order?

Kusalananda
  • 333,661
BSP13
  • 3

1 Answers1

4

The reason for this behaviour is that you included a & at the end of your command, which sends the command to the background and immediately passes on to the next.

The loop should behave as you intended when you remove that &. Note that instead you must put a ; to end this instruction (when placing it all on one line, as originally posted), otherwise the shell will produce an error message.

Also, as pointed out by Stéphane Chazelas, you should make a habit of quoting variable expansions (where approproate, which is in most places); a good introduction can be found here.

AdminBee
  • 22,803
  • Probably also worth noting that the OP also forgot to quote their parameter expansions (assuming they used a POSIX shell like bash). – Stéphane Chazelas Jan 22 '20 at 09:35
  • Thank you, this worked for me..and I learned about the role of & – BSP13 Jan 22 '20 at 09:42
  • You can also mix and match, for example to use 4 processors at a time effectively. GNU has a parallel package that will maintain concurrent streams of process requests, starting a new one to replace those that complete. (Caution: there may be more than one package with similar names.) – Paul_Pedant Jan 22 '20 at 11:54