6

I need to execute the following shell script in my macOS terminal. The loop never executes more than its first iteration.

function execute_function() {
# Launch job
  number_of_jobs=$1
  echo "Launching ${number_of_jobs} jobs"
  for i in {1..$1}; do
    job_id=`head /dev/urandom | tr -dc A-Z0-9 | head -c 6 ; echo ''`
    echo "Launching Job: $job_id"
    echo $i
  done
}

When I run it, I always get:

execute_function 10

    Launching 10 jobs
    Launching Job: XX9BWC
    {1..10}

The same happens if I replace: $1 with $number_of_jobs or "${number_of_jobs}"

Kusalananda
  • 333,661
gogasca
  • 195

2 Answers2

9

Your script is written for zsh but you are executing it with bash.

bash does not support using variables as ranges in brace-expansions.

To resolve this, simply arrange for the script or function be executed in a zsh shell (especially if the script is longer than what you are showing and is using other zsh features). This shell is installed by default on macOS as /bin/zsh. You may add #!/bin/zsh as the first line in the script to have it execute with zsh by default.

See also:

Kusalananda
  • 333,661
6

The problem here is variable in braces expansion.

Try rewriting it to

for ((i=1;i<=$1;i++))
do
  #your code here
done
Jakub Jindra
  • 1,462