title: bash scripting - how to process a comma separated list as input parameters to a function
body: <p>I'm trying to figure out how to pass a comma <code>,</code> separated list as inputs and to have my function process the values one at a time. </p>
  
  <p>My function:</p>
  
  <pre><code>addToWhitelist ()
  {
     host='127.0.0.1'
     db='mytest'
     _mongo=$(which mongo);
     echo "${_ip}";
     read -a arr &lt;&lt;&lt;${_ip};
     for i in ${arr[@]};
     do
       exp="db.account.update({\"account\":'${_account}'},{\$addToSet:{\"ip_list\": {\$each:['${_ip}'] }}})";
       ${_mongo} ${host}/${db} --eval "$exp"
     done
  }
  </code></pre>
  
  <p>I run my script like this:</p>
  
  <p><code>./myscript.sh -m add -a pizzahut -i 123.456.790.007,123.456.790.008</code></p>
  
  <p>My code in progress:</p>
  
  <pre><code>#!/usr/local/bin/bash
  set -e
  set -x
  
  # Usage for getopts
  usage () {
      echo "Example: $0 -m find -a pizzahut"
      echo "Example: $0 -m add -a pizzahut -i 10.10.123.456"
      exit 1;
  }
  
  while getopts ":m:a:i:" o; do
    case "${o}" in
      m)
      _mode=${OPTARG}
           if [[ "${_mode}" != find &amp;&amp; "${_mode}" != add ]]; then
          usage
          fi
      ;;
      a)
      _account=${OPTARG}
      ;;
      i)
      _ip=${OPTARG}
          set -f
          IFS=,
      ;;
      *)
         usage
         ;;
    esac
  done
  shift $((OPTIND-1))
  
  
  getWhitelist ()
  {
     host='127.0.0.1'
     db='mytest'
     _mongo=$(which mongo);
     exp="db.account.find({\"account\":'${_account}'},{ip_list: 1}).pretty();";
     ${_mongo} ${host}/${db} --eval "$exp"
  }
  
  # Read a list
  addToWhitelist ()
  {
     host='127.0.0.1'
     db='mytest'
     _mongo=$(which mongo);
     echo "${_ip}";
     read -a arr &lt;&lt;&lt;${_ip};
     for i in ${arr[@]};
     do
       exp="db.account.update({\"account\":'${_account}'},{\$addToSet:{\"ip_list\": {\$each:['${_ip}'] }}})";
       ${_mongo} ${host}/${db} --eval "$exp"
     done
  }
  
  
  case "${_mode}" in
    'find')
        echo "Finding information for the account ${_account}"
        getWhitelist
        ;;
    'add')
        echo "Adding the following IP: ${_ip}"
        addToWhitelist
        ;;
  esac
  
  set +x
  </code></pre>
  
  <p>However, the problem I'm having when I call that function is that inserts the values as a single string:</p>
  
  <pre><code>  "ip_list" : [
      "123.456.790.006",
      "123.456.790.007,123.456.790.008",
      "123.456.790.009"
    ]
  }
  </code></pre>
  
  <p>Expecting:</p>
  
  <pre><code>  "ip_list" : [
      "123.456.790.006",
      "123.456.790.007",
      "123.456.790.008",
      "123.456.790.009"
    ]
  }
  </code></pre>