I want to pass arguments from a loop into a function func. For simplicity let's say we are working with the loop

for x in {1..5}
    for y in {a..c}
    echo $x$y

I'm just echoing because I don't know what to do. I'd like to run the equivalent of func 1a 1b 1c 2a 2b 2c 3a 3b 3c 4a 4b 4c 5a 5b 5c.

How do I do this?

  • In the loop: y="$y $x"; outside the loop: func $y. This only covers the most simple case. If you have special characters in your list, you need to do something more complex. Mar 11, 2019 at 22:51

1 Answer 1


func {1..5} would be equivalent to func 1 2 3 4 5.

In general, the list of words in a for statement is just like any list of words in a command, so you can just replace the loop with a single invocation of the command, with whatever list you used there moved to the command arguments.

Also, you can use multiple brace expansions together: {1..5}{a..c} would create the list 1a 1b 1c 2a 2b 2c 3a 3b 3c 4a 4b 4c 5a 5b 5c (as distinct words), so in the case you show, func {1..5}{a..c} should work.

If your loop does something more complex to create the arguments to the final command, you can use an array to collect them (in Bash/ksh/zsh). Assuming we have generate_arg that has to be run to produce the arguments to func:

for i in {1..5}; do
    args+=( "$(generate_arg "$i")" )
func "${args[@]}"

(Using an array is better than concatenating the values to a string in that it keeps values with whitespace intact.)

  • There are actually two loops, they're nested. Is there a version of the first instance that works? Mar 11, 2019 at 23:12
  • @CharacterClass, well, now I'm not exactly sure what your situation is then. Can you edit your post to show those nested loops in a bit more detail?
    – ilkkachu
    Mar 11, 2019 at 23:15
  • Thank you. I've updated the question. The loop will serve only to concatenate the variables. Mar 11, 2019 at 23:21
  • @CharacterClass, right, that looks simple since you can use multiple brace expansions. Edited, the section in the middle.
    – ilkkachu
    Mar 11, 2019 at 23:28

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.