I have the following bash script:
#!/bin/bash
while getopts ":h:c:v:s:e" option; do
case $option in
h) # display help
usage
;;
c) # component
component=${OPTARG}
[[ "$component" == "myapp" ]] || usage
;;
v) # version
version=${OPTARG}
[[ -z "$version" ]] || usage
;;
s) # 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 "s 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'"}'
When it runs, I want it to take all the required input opts and make an API call to my AWS account (to create a new version of an AWS "launch template"). But when I run this through ShellCheck I get:
Line 3:
case $option in
^-- SC2220 (warning): Invalid flags are not handled. Add a *) case.
Line 26:
usage {
^-- SC1083 (warning): This { is literal. Check expression (missing ;/\n?) or quote it.
Line 28:
echo "\n"
^-- SC2028 (info): echo may not expand escape sequences. Use printf.
Line 36:
echo "\n"
^-- SC2028 (info): echo may not expand escape sequences. Use printf.
Line 37:
exit ;;
^-- SC1089 (error): Parsing stopped here. Is this keyword correctly matched up?
I can't tell if this is a single error that's causing parsing trouble later on in the script, in multiple places, or if its truly multiple errors. Either way I'm not seeing what's wrong with my -h
case item or the usage()
function. Any idea what the error(s) is/are?
CodePudding user response:
There are multiple problems with your script.
- Every option in
getopt
is one letter.sv
means options
and optionv
. ((
is an arithmetic expression.(( -z ))
means to take the variablez
and apply unary-
on it.[[
is not[
and they are not((
.usage()
is not how you call a function in shell. There is no()
in any call in shell.$USERDATA
is unquoted.