Question

#!/bin/sh

LIST1="0 1"
LIST2="a b"

for L1 in $LIST1; do
    for L2 in $LIST2; do
        echo $L1$2
    done
done

This should shows something like:

0a
0b
1a
1b

How can I express an empty value in the two lists so that the script will show:

emptyempty
a
b
0
0a
0b
1
1a
1b

I tried $(), ${EMPTY}, $* as in LIST1="${EMPTY} 0 1" etc but that value just get ignored and the output starts with 0a, 0b etc. Thank you!

Was it helpful?

Solution

Use arrays:

LIST1=( "" 0 1 )
LIST2=( "" a b )

for L1 in "${LIST1[@]}"; do for L2 in "${LIST2[@]}"; do echo "$L1$L2"; done; done

a
b
0
0a
0b
1
1a
1b

OTHER TIPS

You can use the positional parameters, which act like an array, if you need to this work in a POSIX shell without array support:

set -- "" 0 1
for L1 in "$@"; do
( set -- "" a b
  for L2 in "$@"; do
      echo "$L1$L2"
  done
)
done

The subshell inside the first loop is necessary to avoid overwriting the positional parameters used by the first loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top