I'm writing a simple Bash script that requires argument parsing and have composed the following script that uses getopt to parse short or long arguments provided to the script.
#!/bin/bash
# Default values
EXPERIMENT_NAME=""
SW_IMAGE=""
INSTANCE=""
TOTAL_RUNTIME=""
DATASET=""
PRIORITY=""
# Parse command-line options
ARGS=$(getopt -o n:i:s:r:d:p: --long experiment-name:,sw-image:,instance:,total-runtime:,dataset:,priority: -- "$@")
eval set -- "$ARGS"
# Process options and arguments
while true; do
case "$1" in
-n | --experiment-name)
EXPERIMENT_NAME="$2"
shift 2 ;;
-i | --sw-image)
SW_IMAGE="$2"
shift 2 ;;
-s | --instance)
INSTANCE="$2"
shift 2 ;;
-r | --total-runtime)
TOTAL_RUNTIME="$2"
shift 2 ;;
-d | --dataset)
DATASET="$2"
shift 2 ;;
-p | --priority)
PRIORITY="$2"
shift 2 ;;
--)
shift
break ;;
*)
echo "Invalid option: $1"
exit 1 ;;
esac
done
# Display captured values
echo "EXPERIMENT_NAME: $EXPERIMENT_NAME"
echo "SW_IMAGE: $SW_IMAGE"
echo "INSTANCE: $INSTANCE"
echo "TOTAL_RUNTIME: $TOTAL_RUNTIME"
echo "DATASET: $DATASET"
echo "PRIORITY: $PRIORITY"
I lifted the following line verbatim from another source but do not understand this.
eval set -- "$ARGS"
From what I've read, this relates to use of positional arguments, but I don't understand if this line would enable use of positional arguments to my script in addition to the short/long options or serves some other function. I also don't understand how to parse the syntax in this line.
I would appreciate a breakdown of the syntax and an overall explanation of this line's utility.
From
set --help:So the script will construct a string consisting of the following, which we
evaluate:We will iterate (with the
casestatement andshift 2) through the short / long options and the values passed to them, which are now treated as positional arguments, and will break out of this iteration loop we use for parsing when we reach--, allowing for any other positional arguments (in my example literally the arguments:anyotherpositionalarguments) to be handled downstream of thegetoptparsing.