0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.