处理可选的函数参数

Handle optional function arguments

尝试制作一个最多可以接受 4 个参数的可重用函数(尽管解决方案应该是任意的)。我想 zip 这些带有 AWS CloudFormation 参数的参数,这样如果我不将位置参数传递给 update_stack 它就不会包含在 CF_ARGS.

##
# Update the stack with the given template
# @param: stack_name
# @param: template_body
# @param: [tags]
# @param: [parameters]
##
update_stack() {
    # Handle optional func parameters
    CF_PARAMS=("--stack-name" "--template-body" "--tags" "--parameters")
    # Only include a param if we have a value supplied as an argument. (+1 to ignore script name)
    CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done))

    # Should make the call as "aws cloudformation create-stack --stack-name  --template-body "
    # If  or  are not supplied then it should not add them to CFG_ARGS
    aws cloudformation create-stack "${CFG_ARGS[@]}"
}

我想我的 CF_ARGS 构造按预期工作 我只是不知道如何在 [=41] 中 apply 参数=] 函数调用和我的 google 技能无法找到解决方案。请帮忙!

谢谢, 亚历克斯

PS。我从 awscli 得到的错误是(可能是双引号?):

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument --stack-name is required

编辑 (1):

感谢@Barmar 提供的第一个解决方案。这让我犯了这个错误:

Unknown options: Description:, Handles, Authentication, &, Access, permissions, Resources:, ##, #, Policies, ##, PolicyDevelopers:, Type:, AWS::IAM::Policy, Properties:, PolicyName:, Developers-cf, #, @todo:, Remove, suffix, PolicyDocument:, Version:, "2012-10-17", Statement:, -, Effect:, Allow, NotAction:, -, iam:*, -, sts:AssumeRole, ...

“--template-body”参数是一个多行字符串(确切地说是 YAML 文件),是否可以对每个参数加双引号? :/

您正在将 CF_ARGS 设置为单个字符串,而不是数组。您需要用另一组括号将其包裹起来以获得一个数组。

CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done))

并使其将 for 循环的每一行输出视为一个参数,您可以将 IFS 设置为仅包含换行符:

IFS=$'\n'
CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done))