1

I currently have 3 variables which are either set to true or false. I have 5 such scenarios:

var1 = T; var2 = T; var3 = T
var1 = T; var2 = T; var3 = F
var1 = F; var2 = T; var3 = F
var1 = F; var2 = F; var3 = T
var1 = F; var2 = F; var3 = F

I would like to create a loop in my bash script that is able to loop over each of the above 5 scenarios and set the variables accordingly. Is there a way to put everything in a matrix-like array and call them out? If I do:

for var1 in T F; do for var2 in T F; do for var3 in T F; do
# execute whatever here.....
done
done
done

It obviously goes over what I want, and if I were to scale this up to many variables and many scenarios, it becomes unfeasible. In summary, I would like have three variables set for each loop that contains the values in each of the 5 scenarios. Is there a way to program this in a bash script? thanks.

user321627
  • 2,350
  • 4
  • 20
  • 43
  • 1
    Since you only have five "scenarios" from the three variables, instead of the full eight that one would normally have, there must be some special rules about those "scenarios" and the combinations possible. You need to spell out those rules first to be able to start. – Some programmer dude Jun 21 '18 at 06:01
  • You would generally see this done using 3-indexed arrays. E.g. `var1=(T T F F F); var2=(T T T F F); var3=(T F F T F);` then using a C-Style loop, `for ((i = 0; i < ${#var1[@]}; i++)); do if [ "${var1[i]}" = 'T' ] && [ "${var2[i]}" = 'T' ] && [ "${var3[i]}" = 'T' ]; then .... elif ....fi; done` or you can use a `case` statement to check values. By using an indexed array for each, you can coordinate the check on each record in each array, e.g. all `0` elements, then all `1` elements, etc... (you can also included checks to insure each array/vector has an equal number of elements) – David C. Rankin Jun 21 '18 at 06:19
  • Write a function `f()` then do `f 1 1 1` then `f 1 1 0` etc – Mark Setchell Jun 21 '18 at 06:23

2 Answers2

1

What you are trying to achieve should be achievable by arrays

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

And then declaring your scenarios in a 2d matrix and loop over it

How to declare 2D array in bash

mirmdasif
  • 6,014
  • 2
  • 22
  • 28
1

Here are a few ideas...


Feed into a loop

line=1
while read var1 var2 var3; do
   echo $line: $var1, $var2, $var3
   ((line+=1))
done <<EOF
T T T
T T F
F T F
F F T
F F F
EOF

Output

1: T, T, T
2: T, T, F
3: F, T, F
4: F, F, T
5: F, F, F

Feed into a loop

line=1
cat <<EOF |
T T T
T T F
F T F
F F T
F F F
EOF

while read var1 var2 var3; do
   echo $line: $var1, $var2, $var3
   ((line+=1))
done

Output

1: T, T, T
2: T, T, F
3: F, T, F
4: F, F, T
5: F, F, F

Use a function

func(){
   var1=$1; var2=$2; var3=$3
   echo $var1, $var2, $var3
}

func 1 1 1
func 1 1 0
func 0 1 0
func 0 0 1
func 0 0 0

Output

1, 1, 1
1, 1, 0
0, 1, 0
0, 0, 1
0, 0, 0
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432