I'm trying to create a script that has an option that will contain arbitrary text (including spaces) surrounded by quotes and this is proving difficult to search for and implement.
Basically the behavior I would like to have is docker_build_image.sh -i "image" -v 2.0 --options "--build-arg ARG=value", this will be a helper script for simplifying versioning docker images with our build server.
The closest I've come to successfully grabbing the --options value gives me an error from getopt, "unrecognized option '--build-arg ARG=value'.
The full script is below
#!/usr/bin/env bash
set -o errexit -o noclobber -o nounset -o pipefail
params="$(getopt -o hi:v: -l help,image:,options,output,version: --name "$0" -- "$@")"
eval set -- "$params"
show_help() {
cat << EOF
Usage: ${0##*/} [-i IMAGE] [-v VERSION] [OPTIONS...]
Builds the docker image with the Dockerfile located in the current directory.
-i, --image Required. Set the name of the image.
--options Set the additional options to pass to the build command.
--output (Default: stdout) Set the output file.
-v, --version Required. Tag the image with the version.
-h, --help Display this help and exit.
EOF
}
while [[ $# -gt 0 ]]
do
case $1 in
-h|-\?|--help)
show_help
exit 0
;;
-i|--image)
if [ -n "$2" ]; then
IMAGE=$2
shift
else
echo -e "ERROR: '$1' requires an argument.\n" >&2
exit 1
fi
;;
-v|--version)
if [ -n "$2" ]; then
VERSION=$2
shift
else
echo -e "ERROR: '$1' requires an argument.\n" >&2
exit 1
fi
;;
--options)
echo -e "OPTIONS=$2\n"
OPTIONS=$2
;;
--output)
if [ -n "$2" ]; then
BUILD_OUTPUT=$2
shift
else
BUILD_OUTPUT=/dev/stderr
fi
;;
--)
shift
break
;;
*)
echo -e "Error: $0 invalid option '$1'\nTry '$0 --help' for more information.\n" >&2
exit 1
;;
esac
shift
done
echo "IMAGE: $IMAGE"
echo "VERSION: $VERSION"
echo ""
# Grab the SHA-1 from the docker build output
ID=$(docker build ${OPTIONS} -t ${IMAGE} . | tee $BUILD_OUTPUT | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')
# Tag our image
docker tag ${ID} ${IMAGE}:${VERSION}
docker tag ${ID} ${IMAGE}:latest