title: Distributing lines of commands using bash script
body: <p>I'm trying to implement trivial parallelization where lines of commands are distributed among separate processes. For that purpose I wrote this script that I named <code>jobsel</code>:</p>
  
  <pre><code>(only "#! /bin/bash" and help message is omitted)
  
  slots=$1
  sel=$2
  
  [[ $slots -gt 0 ]] || die_usage
  [[ $sel -lt $slots ]] || die_usage
  
  i=0
  while read line
  do
          (( i % slots == sel )) &amp;&amp; eval $line
          i=$(( i + 1 ))
  done
  
  # in case the last line does not end with EOL
  if [[ $line != "" ]]; then
          (( i % slots == sel )) &amp;&amp; eval $line
          i=$(( i + 1 ))
  fi
  </code></pre>
  
  <p>I put <code>eval</code> because I couldn't use redirection or pipe in the commands without it.</p>
  
  <p>When I run this like <code>$HOME/util/jobsel 22 0 &lt; cmds</code> on a console emulator when <code>cmds</code> is a file that contains lines like <code>echo 0 &gt;&gt; out</code> with increasing numbers, it outputs, as expected, <code>0, 22, 44...</code> in separate lines. Good so far.</p>
  
  <p>So I put this to work. But when I ran this through secure shell, I ran it through <code>at</code> with backgrounding (ending each line with <code>&amp;</code>). Then there is a problem. When I entered 8 lines, 21 processes started! <code>ps -AFH</code> printed processes with identical command and different pIDs. All work processes were at the same level, directly under init. My program does not create child processes anyway.</p>
  
  <p>Puzzled, I tried the <code>echo 0 &gt;&gt; out</code> script through <code>at</code> then the output contained duplicate lines. Still finding it hard to believe, and thinking simultaneous appending might have caused the anomaly, I used other methods to confirm that some lines were run multiple times.</p>
  
  <p>Moreover, there was no such anomaly when everything was run in terminal or when I created separate <code>at</code> job for each worker process.</p>
  
  <p>But how can this happen? Is something wrong with my script? Does <code>at/atd</code> have some bug?</p>