Skip to content

Instantly share code, notes, and snippets.

@linguisticmind
Last active July 19, 2024 00:11
Show Gist options
  • Select an option

  • Save linguisticmind/41ce35abcc407128283ff13a1c765594 to your computer and use it in GitHub Desktop.

Select an option

Save linguisticmind/41ce35abcc407128283ff13a1c765594 to your computer and use it in GitHub Desktop.
A Bash script template | "[Bash scripting #1] Parsing options with getopt" (https://youtu.be/Ok9hncgOtxE) | Mindful Technology
#!/usr/bin/env bash
function print_demo_msg {
printf '\x1b[38;5;243;48;5;233m%s\x1b[49;39m\n' "$1"
printf '%s\n' "$2" #| batcat -pl bash --color=always --theme='OneHalfDark'
}
version=0.1.0
getopt -T > /dev/null
[[ $? != 4 ]] && { printf '[%s] %s\n' "${BASH_SOURCE##*/}" 'Enhanced getopt is required to run this script.' >&2; exit 1; }
print_demo_msg 'Initial arguments' "$(printf '%q ' "$0" "$@")"
help=''
opts=$(getopt -n "${BASH_SOURCE##*/}" -o 'c,C,h,V,' -l 'color,no-color,help,version,' -- "$@")
[[ $? != 0 ]] && exit 1
print_demo_msg 'Value of opts' "$(declare -p opts)"
eval set -- "$opts"
print_demo_msg 'Arguments after eval' "$(printf '%q ' "$0" "$@")"
opt_color=1
test -f "${XDG_CONFIG_HOME:-$HOME/.config}"'/test-script/config.bash' && source "$_"
while true; do
case $1 in
-c | --color ) opt_color=1; shift ;;
-C | --no-color ) opt_color=; shift ;;
-h | --help ) printf '%s\n' "$help"; exit ;;
-V | --version ) printf '%s\n' "$version"; exit ;;
-- ) shift; break ;;
* ) printf '[%s] %s\n' "${BASH_SOURCE##*/}" 'Internal error: unable to parse option `'"$1"'`.' >&2; exit 1 ;;
esac
done
print_demo_msg 'Arguments after parsing' "$(printf '%q ' "$0" "$@")"
printf \
${opt_color:+'\x1b[32m'}'[%s] %s'${opt_color:+'\x1b[39m'}'\n' \
"${BASH_SOURCE##*/}" \
'This is a getopt demo.' >&2
#!/usr/bin/env bash
version=0.1.0
getopt -T > /dev/null
[[ $? != 4 ]] && { printf '[%s] %s\n' "${BASH_SOURCE##*/}" 'Enhanced getopt is required to run this script.' >&2; exit 1; }
help=''
opts=$(getopt -n "${BASH_SOURCE##*/}" -o 'c,C,h,V,' -l 'color,no-color,help,version,' -- "$@")
[[ $? != 0 ]] && exit 1
eval set -- "$opts"
opt_color=1
test -f "${XDG_CONFIG_HOME:-$HOME/.config}"'/test-script/config.bash' && source "$_"
while true; do
case $1 in
-c | --color ) opt_color=1; shift ;;
-C | --no-color ) opt_color=; shift ;;
-h | --help ) printf '%s\n' "$help"; exit ;;
-V | --version ) printf '%s\n' "$version"; exit ;;
-- ) shift; break ;;
* ) printf '[%s] %s\n' "${BASH_SOURCE##*/}" 'Internal error: unable to parse option `'"$1"'`.' >&2; exit 1 ;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment