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
}
  • 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. – Gilles Mar 27 '17 at 23:31
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.

  • 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? – dimas Mar 27 '17 at 15:19
  • @dimas ${#docCodeArr[*]} is the length of the array. You can read all about bash arrays in man bash. – Satō Katsura Mar 27 '17 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.