There are some codes in bash that break my head off and leave me without a clew why is not working .
On this code
Code:
#!/bin/bash
# random variable
var1="49274"
echo "Example variable is : $var1"
#simple loop with 5 steps
for i in 1 2 3 4 5
do
# This command will call the current variable and will search
# if $i from loop is in the var , loop starts in 1 and finishes in 5
test=$(echo "$var1" | grep -o $i)
# If grep did not found the $i value on var then set the variable
# ex$i ($i could be from 1 to 5) some text , else then found that
#number in the var and set the text in 2nd var different
if [[ -z "$test" ]]
then
ex$i="not there"
else
ex$i="is there"
fi
done
# Here the loop as finished and i expect that all the (ex$) variables
# have some text in there
# However it is popping an error
echo "1 = $ex1"
echo "2 = $ex2"
echo "3 = $ex3"
echo "4 = $ex4"
echo "5 = $ex5"
Yes , i know what you are thinking , you are probably thinking that i could set the final "echo" in code inside the loop like this and solved the problem
Code:
#!/bin/bash
# random variable
var1="49274"
echo "Example variable is : $var1"
#simple loop with 5 steps
for i in 1 2 3 4 5
do
# This command will call the current variable and will search
# if $i from loop is in the var , loop starts in 1 and finishes in 5
test=$(echo "$var1" | grep -o $i)
# If grep did not found the $i value on var then set the variable
# ex$i ($i could be from 1 to 5) some text , else then found that
#number in the var and set the text in 2nd var different
if [[ -z "$test" ]]
then
echo "$i= not there"
else
echo "$i=is there"
fi
done
But i need it to be like it is in the first example , setting a different variable .
-------------------------------------------------------------------
Final code fixed :
Code:
#!/bin/bash
var1="49274"
echo "Example variable is : $var1"
for i in 1 2 3 4 5
do
test=$(echo "$var1" | grep -o $i)
if [[ -z "$test" ]]
then
ex[$i]="not there"
else
ex[$i]="is there"
fi
done
echo "1 = ${ex[1]}"
echo "2 = ${ex[2]}"
echo "3 = ${ex[3]}"
echo "4 = ${ex[4]}"
echo "5 = ${ex[5]}"