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
  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

When I run it, I always get:

execute_function 10

    Launching 10 jobs
    Launching Job: XX9BWC

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


The problem here is variable in braces expansion.

Try rewriting it to

for ((i=1;i<=$1;i++))
  #your code here
  • That worked perfectly – gogasca Apr 2 '19 at 5:22

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:

  • 1
    include #!/bin/zsh as first line. (you may need to check the path. – ctrl-alt-delor Apr 2 '19 at 7:57
  • what about #!/usr/bin/env zsh? – Jakub Jindra Apr 2 '19 at 8:46
  • @JakubJindra That would work to, but the default location of zsh is /bin/zsh on macOS. Obviously, you may want to use env if you need to use a 3rd-party installation of zsh. However, this is not the essence of this particular question. – Kusalananda Apr 2 '19 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.