-3

When I execute below script it works fine:

if [[ "[1,2,3]" =~ .*1.* ]]; then
techStatus=1
else 
techStatus=0;
fi
echo $techStatus

Output is 1

But when we changes it to variable it does not work.

var1=[1,2,3]
var2=1
if [[ "$var1" =~ .*"$var2".* ]]; then
techStatus=1
else 
techStatus=0;
fi
echo $techStatus

Output is 0.

Please help me figure out what is wrong here.

vinay
  • 954
  • 1
  • 9
  • 25

1 Answers1

0

A better & readable approach would be to convert var1 to array and loop through var1.

var1=(1 2 3)
var2=1
for elem in "${var1[@]}"; do
    if [[ "$elem" -eq "$var2" ]]; then
        techStatus=1
        break
    else
        techStatus=0
    fi
done
echo "$techStatus"
apatniv
  • 1,393
  • 7
  • 11
  • 1
    Key by array indices and you don't even have to loop. `var1=( [1]=1 [2]=1 [3]=1 ); if [[ ${var1[$var2]} ]]; then techStatus=1; else techStatus=0; fi` -- if the keys can be non-numeric that means making it an associative array, but that's not much of a change. – Charles Duffy Sep 23 '18 at 14:52
  • 1
    ...that said, posing this as an answer implies that you think the question could be closed as a duplicate of [check if a bash array contains a value](https://stackoverflow.com/questions/3685970/check-if-a-bash-array-contains-a-value), insofar as the essential elements are all covered there. – Charles Duffy Sep 23 '18 at 18:30