bash scipt - 如何在getopts中测试多个条件

时间:2017-10-16 03:53:41

标签: bash shell unix getopts

我需要帮助找出我的bash脚本中的逻辑,我使用getopts传递参数。

我在哪里检查:

如果标记-m = find,那么 传递参数./script.sh -m find -a myacccount

如果标记-m = add,那么 传递其他参数./script.sh -m add -a myaccount -i 10.10.12.123

例如:

#!/usr/local/bin/bash
set -e
set -x

# Usage for getopts
usage () {
    echo "Usage: $0 -m <find|add> -a <accountname> -i <10.10.123.456>"
    echo "Example: $0 -m find -a dominos"
    echo "Example: $0 -m add -a dominos -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}
    ;;
    *)
       usage
       ;;
  esac
done
shift $((OPTIND-1))



#Functions
getWhitelist ()
{
   host='127.0.0.1'
   db='mytest'
   _mongo=$(which mongo);
   exp="db.myaccount.find({\"account\":'${_account}'},{ip_list: 1}).pretty();";
   ${_mongo} ${host}/${db} --eval "$exp"
}

addToWhitelist ()
{
   host='127.0.0.1'
   db='mytest'
   _mongo=$(which mongo);
   exp="db.myaccount.update({\"account\":'${_account}'},{\$addToSet:{\"ip_list\": {\$each:['${_ip}'] }}})";
   ${_mongo} ${host}/${db} --eval "$exp"
}


# Logic
if [[ "${_mode}" == "find" ]]; then
    echo "Finding information for the account $m"
    getWhitelist
else
    echo "wrong mode: find or add"
    exit 1
fi

if [[ "${_mode}" == "add" ]]; then
    echo "Adding the following IP: ${_ip}"
    addToWhitelist
else
    exit 1
fi

set +x

我无法检查add是否有效。我需要这段逻辑的帮助,以便我可以将函数调用到addToWhitelist

基本上,我想要做的是当我传入-m add时,我需要传递-i <ipaddress>并调用函数addToWhitelist

感谢您的帮助。

0 个答案:

没有答案