I'm trying to figure out how to pass a comma ,
separated list as inputs and to have my function process the values one at a time.
My function:
addToWhitelist ()
{
host='127.0.0.1'
db='mytest'
_mongo=$(which mongo);
echo "${_ip}";
read -a arr <<<${_ip};
for i in ${arr[@]};
do
exp="db.account.update({\"account\":'${_account}'},{\$addToSet:{\"ip_list\": {\$each:['${_ip}'] }}})";
${_mongo} ${host}/${db} --eval "$exp"
done
}
I run my script like this:
./myscript.sh -m add -a pizzahut -i 123.456.790.007,123.456.790.008
My code in progress:
#!/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 && "${_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 <<<${_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
However, the problem I'm having when I call that function is that inserts the values as a single string:
"ip_list" : [
"123.456.790.006",
"123.456.790.007,123.456.790.008",
"123.456.790.009"
]
}
Expecting:
"ip_list" : [
"123.456.790.006",
"123.456.790.007",
"123.456.790.008",
"123.456.790.009"
]
}