0

We have cgi application written in bash scripts. I am trying to understand how the code snippet below works. Basically its a dropdown menu and the choices is governed by _getDocType logic. How does the function take the value for "imgCodeStr"? All of this code is under one cgi file written in bash.

HTML generating function

<select id="docType" name="doctype" style="width:100%">
        $(_getDocType)
</select>

where _getDocType function definition is

_getDocType()
{
        tmpIfs=IFS
        IFS="#" docCodeArr=($imgCodeStr) <-- Please explain this specifically
        IFS=tmpIfs

        for (( i=0; i<${#docCodeArr[*]}; i++ ))
        do
                echo "<option value=\"${docCodeArr[$i]}\">${docCodeArr[$i]}"
                echo "</option>"
        done
}
1
  • Note that there's a bug: tmpIfs=IFS and IFS=tmpIfs should be tmpIfs=$IFS and IFS=$tmpIfs. This would bite you if the rest of the script relied on the value of IFS. Commented Mar 27, 2017 at 23:31

1 Answer 1

3

Here's a simpler example:

var='a#b#c'
IFS=\# arr=($var)
echo "${arr[@]}"

The construct arr=(...) builds an array. Since IFS is set to #, the value of var is split into words at # instead of spaces, so

IFS=\# arr=($var)

is equivalent to

arr=(a b c)

Thus the array arr is formed of elements a, b, and c.

For the same reason, docCodeArr is an array, made of the value of imgCodeStr split at #. That's about all there is to it.

Beware that if the value of imgCodeStr contains wildcard characters (characters among \[?*), the shell will expand the wildcard pattern to matching file names. To avoid this, put set -f before that line to disable wildcard expansion. If you need to reenable wildcard expansion, use set +f.

2
  • thanks for the clear explanation. I have a follow up question. In the for loop section, the second argument is a limit where i is lesser than doccodearr array. Can you explain a bit how the length of this array was derived? Commented Mar 27, 2017 at 15:19
  • @dimas ${#docCodeArr[*]} is the length of the array. You can read all about bash arrays in man bash. Commented Mar 27, 2017 at 15:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.