0

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}
do
    for y in {a..c}
    do
    echo $x$y
    done
done

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?

1
  • 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. Commented Mar 11, 2019 at 22:51

1 Answer 1

2

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:

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

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

4
  • There are actually two loops, they're nested. Is there a version of the first instance that works? Commented 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
    Commented Mar 11, 2019 at 23:15
  • Thank you. I've updated the question. The loop will serve only to concatenate the variables. Commented 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
    Commented Mar 11, 2019 at 23:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .