Home > OS >  Serial Incremental bash loop running 2 processes in parallel
Serial Incremental bash loop running 2 processes in parallel

Time:08-12

#!/bin/bash -l 
ind() {
if [[ $1 -lt 10 ]] ; then
 return 00$1
elif [[ $1 -lt 100 ]] ; then
 return 0$1
elif [[ $1 -lt 1000 ]] ; then
 return $1
fi
}

for i in `seq 0 2 127`
do    
  j=$(($i 1))
  ii=$(ind $i)
  jj=$(ind $j)
  echo "ii jj here"  "${ii}" "${jj}" 
runA $ii & runA $jj &
done

I would expect this to give me output like

000 001

002 003

004 005

...

010 011

...

126 127

so that in this loop I will run 2 jobs in parallel with $ii and $jj being their respective inputs, just shown symbolically, no output is produced by them here.

It gives me nothing:

ii jj here
ii jj here

I must be doing something very silly, fundamentally wrong, although I am quite experienced. Can you please help me? This is not a homework.

Many thanks for reading. ....

CodePudding user response:

Ah, I was returning a return status of the process, not a result. https://linuxize.com/post/bash-functions/#:~:text=To invoke a bash function,any calls to the function.

corrected code is:

#!/bin/bash -l 
ind() {
if [[ $1 -lt 10 ]] ; then
 res="00$1"
elif [[ $1 -lt 100 ]] ; then
 res="0$1"
elif [[ $1 -lt 1000 ]] ; then
 res="$1"
fi
}

for i in `seq 0 2 127`
do    

  ind $i
  ii=$res
   
  j=$(($i 1))
  ind $j

  jj=$res
  echo "ii jj here"  "${ii}" "${jj}" 
done

CodePudding user response:

Here are some bash idioms that'll make your code a little better:

#!/bin/bash

for i in {0..127..2}
do
  printf -v ii 'd' "$i"
  printf -v jj 'd' "$((i 1))"
  echo "$ii" "$jj" 
  runA "$ii" & runA "$jj" &
done

wait

general remarks:

  • a rule of thumb is to always double quote your variables expansions.

  • shell functions normally output the result and return 0 on success (or [1-127] when there's a problem)

  • seq can generally be replaced with a bash "range", which is safer; for using for i in $(seq ...) you have to make sure that IFS isn't messed-up.

  • using printf for formatting a string is easier. And bash printf -v var ... is more accurate than var=$(printf ...) because it doesn't strip the trailing newlines.

  • add a wait at the end when you fire sub-processes

  •  Tags:  
  • bash
  • Related