2

Example:

$ eval echo "{x,y,z}\ --opt\; "
x --opt; y --opt; z --opt;

Assume that the 2nd list is {1,2,3} and its length is equal to the length of the 1st (initial) list.

Questions:

  1. How to make bash produce:
x --opt 1; y --opt 2; z --opt 3;
  1. How to make bash produce (i.e. to refer the elements from the {x,y,z} list):
x --opt x; y --opt y; z --opt z;

One-liners are preferred.

2 Answers 2

4

Brace expansion would create all possible pairs, it doesn't walk both the lists in parallel:

$ echo {x,y,z}' --opt; '{1,2,3}
x --opt; 1 x --opt; 2 x --opt; 3 y --opt; 1 y --opt; 2 y --opt; 3 z --opt; 1 z --opt; 2 z --opt; 3

To produce the desired output, you need to use something else. For example, loop over the indices of an array:

#! /bin/bash
opt1=(x y z)
opt2=(1 2 3)
for i in "${!opt1[@]}" ; do
    printf '%s --opt %s; ' "${opt1[i]}" "${opt2[i]}"
done
echo

Or, use associative arrays:

#! /bin/bash
declare -A opts=([x]=1 [y]=2 [z]=3)
for i in "${!opts[@]}" ; do
    printf '%s --opt %s; ' "$i" "${opts[$i]}"
done
echo
1

As choroba pointed out, using {x..z}' --opt '{1..3}';' would generate all possible combinations of strings.

From the list of all possible combinations, 1 through to 9, we want every fourth combination, 1, 5, and 9.

set -- {x..z}' --opt '{1..3}';'
eval echo '${'{1..9..4}'}'

Or, using arrays, fetching elements 0, 4, and 8.

strings=( {x..z}' --opt '{1..3}';' )
eval echo '${strings['{0..8..4}']}'

Note that I would never ever write real code like this and that the code above generates strings that are virtually useless for use as real commands/arguments as they would need to be explicitly split by the shell.

The code is purely presented as an interesting tidbit.

You must log in to answer this question.

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