I am currently writing a BASH script in which I would like to use both positional and optional arguments. The positional arguments must occur at the location specified (ex: $1, $2) while the optional arguments can occur at any position denoted by their command line flag. Here is my script:
#!/usr/bin/env bash
usage() {
cat << EOF
Usage: progam ACTION NAME -k KEY_NAME
ACTION ...... The program action to initiate
NAME ........ The name of the object to create
KEY_NAME .... The key name to use
EOF
}
ACTION=$1
NAME=$2
KEY_NAME=""
while getopts "k:" opt; do
case $opt in
k) KEY_NAME=$OPTARG; ;;
[?]) usage && exit 1;
esac
done
if [[ ! $ACTION ]]; then
echo "Please select an action."
exit 1
fi
if [[ ! $NAME ]]; then
echo "Please include a name for the object."
exit 1
fi
if [[ "$KEY_NAME" != "" ]]; then
python3 -m program $ACTION -k $KEY_NAME -n $NAME
else
echo "Please include a key name."
exit 1
fi
exit 0
to run the program I would expect to be able to do the following:
fun_bash [action] [name] -k [key_name]
Where the things in brackets would be replaced by actual strings. When I execute, I always hit the condition that the key name does not exist:
Please include a key name.
How can I include mandatory positional arguments and optional command line flags within the same script?
getopts. If you want to allow this convention, use a library (like GNUgetopt) that supports it.getoptsnever sees-k, because it has a non-zero exit status when it sees its first non-optional argument.