【问题标题】:Case item and function parsing issues with bash and getoptsbash 和 getopts 的案例项目和函数解析问题
【发布时间】:2022-08-23 22:35:24
【问题描述】:

我有以下 bash 脚本:

#!/bin/bash
while getopts \":h:c:v:sv:e\" option; do
  case $option in
    h) # display help
      usage()
      ;;
    c) # component
      component=${OPTARG}
      (( \"$component\" == \"myapp\")) || usage();
      ;;
    v) # version
      version=${OPTARG}
      (( -z \"$version\")) || usage();
      ;;
    sv) # source version
      sourceVersion=${OPTARG}
      (( -z \"$sourceVersion\")) || usage();
      ;;
    e) # environment
      env=${OPTARG}
      (( \"$env\" = \"dev\" || \"$env\" = \"staging\" || \"$env\" = \"prod\")) || usage();
      ;;
  esac
done

usage() {
  echo \"Copy an existing launch template version and update it with a new one.\"
  echo \"\\n\"
  echo \"Syntax: $0 -c <component> -v <version> -sv <sourceVersion> -e <env> [-h]\"
  echo \"options:\"
  echo \"c       name of the component (must be myapp)\"
  echo \"v       the new version to create\"
  echo \"sv      the source version to copy from\"
  echo \"e       environment (must be dev, staging or prod)\"
  echo \"h       display help\"
  echo \"\\n\"
  exit ;;
}

if [ \"$env\" = \"dev\" ]
then
  ltId=abc
elif [ \"$env\" = \"staging\" ]
then
  ltId=def
elif [ \"$env\" = \"prod\" ]
then
  ltId=ghi
else
  echo \"env not supported\"
  exit 1
fi

USERDATA=$(base64 ./core/\"$component\"-user-data-\"$version\".sh)
aws ec2 create-launch-template-version \\
  --launch-template-id $ltId \\
  --launch-template-name $component-$version \\
  --source-version $sourceVersion
  --launch-template-data \'{\"UserData\": \"\'$USERDATA\'\"}\'

当它运行时,我希望它获取所有必需的输入选项并对我的 AWS 账户进行 API 调用(以创建 AWS“启动模板”的新版本)。但是当我通过ShellCheck 运行它时,我得到:

Line 4:
    h) # display help
    ^-- SC1009 (info): The mentioned syntax error was in this case item.
 
Line 5:
      usage()
      ^-- SC1073 (error): Couldn\'t parse this function. Fix to allow more checks.
 
Line 6:
      ;;
      ^-- SC1064 (error): Expected a { to open the function definition.
      ^-- SC1072 (error): Fix any mentioned problems and try again.

我无法判断这是否是单个错误导致稍后在脚本中、多个地方出现解析问题,或者它是否确实存在多个错误。无论哪种方式,我都没有看到我的 -h 案例项目或 usage() 函数有什么问题。知道错误是什么吗?

    标签: bash getopts


    【解决方案1】:

    您的脚本存在多个问题。

    • getopt 中的每个选项都是一个字母。 sv 表示选项 s 和选项 v
    • (( 是一个算术表达。 (( -z )) 表示取变量 z 并对其应用一元 -[[ 不是 [,它们也不是 ((
    • usage() 不是你在 shell 中调用函数的方式。在 shell 中的任何调用中都没有 ()
    • $USERDATA 未引用。

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2011-02-22
      • 2019-10-16
      • 2011-10-17
      • 2021-09-12
      • 2013-02-21
      • 1970-01-01
      • 2017-01-18
      • 2011-11-26
      相关资源
      最近更新 更多