0

I have the following in my bash file:

echo "Spawning $1 processes"
for i in {1..$1}
do
    (go run loadgen.go $2 &)
    echo "done."
done

However, I can only seem to get my go file to execute once. I know that they're started in the background, but each of my go files should append to the same log file (I can reproduce this by running my bash script multiple times). Am I doing something wrong to get this to iterate multiple times?

JimB
  • 104,193
  • 13
  • 262
  • 255
MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • 3
    This is not possible: `{1..$1}`. Brace expansion happens before variable expansion. – Cyrus May 15 '20 at 19:14
  • Is that specific to `go`? Also, I think that a look at the process tree would help you. ;) – Ulrich Eckhardt May 15 '20 at 19:14
  • @Cyrus: Try it, it assumes that `$1` evaluates to a number. – Ulrich Eckhardt May 15 '20 at 19:15
  • @Cyrus - based on your comment, I updated it to `for ((i=0;i<=$1;i++))` and that seems to work. I'd be interested in knowing the full explanation though. – MrDuk May 15 '20 at 19:20
  • It has nothing to do with go, but with the bash script. The bash interpreter first expands the {1..$1} part, it assumes you meant {1..1}, then it replaces $1 with the value you provided, but it is already too late, since bash rewrote {1..$1} to {1..1}. – gerwin May 15 '20 at 19:25
  • As first step bash tries to expand `{1..$1}`. `$1` is here only a string and bash can't expand `{1..$1}`. It remains `{1..$1}`. Then bash expands `$1` to `3` (e.g.) and now it gets `{1..3}`. Your loop runs only once while `$i` contains string `{1..3}`. – Cyrus May 15 '20 at 19:25
  • I suggest to replace `i=0` with `i=1` or replace `<=` with `<`. – Cyrus May 15 '20 at 19:31
  • 1
    This is also covered in [BashPitfalls #33](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D). – Charles Duffy May 15 '20 at 19:46
  • 1
    The order of expansion is described by the bash manual: `PAGER='less +/^Expansion' man bash` and the online one: https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html, although `{1..$n}` works in `zsh` – Jetchisel May 15 '20 at 19:58

0 Answers0