Reputation: 25865
i write below script
#!/bin/bash
str1="apple"
str2="banana"
str3="NA"
str4="lumia"
str5="nokia"
let maxarg=5
checkindex()
{
while [ $maxarg -gt 0 ]
do
str="${str$maxarg}" //here is problem
echo -e $str
if [ "${str}" == "NA" ]
then
break
fi
((maxarg--))
done
printf "Index is %d\n" $maxarg
}
checkindex
when exicuting it i got str1,str2....Index is 0
output but what i want to print apple,banana....Index is 3
means catch the index where NA
string found. Using str="${str$maxarg}"
i tried to redirect the output of str1,str2....str5
in str
because i am not going to use any switch case
or if..else
for comparing each string.
Any help?
Upvotes: 0
Views: 81
Reputation: 123458
You need to refer to indirect expansion. Replacing the line
str="${str$maxarg}" //here is problem
with
tmp="str${maxarg}" # This sets the variable tmp to str1 and so on
str=${!tmp} # This performs indirect expansion to retrieve
# the value of the variable name stored in tmp
should make it work.
Upvotes: 2