Skip to content

Instantly share code, notes, and snippets.

@rinormaloku
Last active July 8, 2020 07:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rinormaloku/46b89e10d0f06e74fb6c6460af347a65 to your computer and use it in GitHub Desktop.
Save rinormaloku/46b89e10d0f06e74fb6c6460af347a65 to your computer and use it in GitHub Desktop.
named arguments sample for bash
#!/bin/bash
#set -e
help() {
cat <<EOF
A minimalistic script to showcase named arguments in bash.
The following flags are required.
--req-arg If required arg is not specified execution is interrupted.
The following flags are optional.
--opt-arg Variable defaults to 'default'
EOF
exit 1
}
while [[ $# -gt 0 ]]; do
case ${1} in
--req-arg)
REQUIRED_ARG="$2"
shift
;;
--opt-arg)
OPTIONAL_ARG="$2"
shift
;;
*)
help
;;
esac
shift
done
# Exiting if required argument is not defined
[ -z "${REQUIRED_ARG}" ] && echo "--req-arg is required, type --help for help" && exit 1;
# Defaulting the optional argument
[ -z "${OPTIONAL_ARG}" ] && OPTIONAL_ARG=default
echo "--req-arg=$REQUIRED_ARG"
echo "--opt-arg=$OPTIONAL_ARG"
@rinormaloku
Copy link
Author

rinormaloku commented Dec 24, 2019

Applying named arguments

$ ./named-arguments.sh --req-arg very-important --opt-arg not-so-important
--req-arg=very-important
--opt-arg=not-so-important

Optional argument defaulting to the default value

$ ./named-arguments.sh --req-arg very-important
--req-arg=very-important
--opt-arg=default

Missing Required argument

$ ./named-arguments.sh --opt-arg not-so-important       
--req-arg is required, type --help for help

Help

$ ./named-arguments.sh --help
A minimalistic script to showcase named arguments in bash.

The following flags are required.
       --req-arg        If required arg is not specified execution is interrupted.

The following flags are optional.
       --opt-arg        Variable defaults to 'default'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment