Skip to content

Instantly share code, notes, and snippets.

@xlith
Last active February 20, 2023 08:39
Show Gist options
  • Save xlith/6a2edb0c3f3b92862bd3ab12217d4f3d to your computer and use it in GitHub Desktop.
Save xlith/6a2edb0c3f3b92862bd3ab12217d4f3d to your computer and use it in GitHub Desktop.
Templete for a new bash script
#!/usr/bin/env bash
: Setup environment
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
filename=$(basename "$0")
cd "$(dirname "$0")"
: Load .env file if exists
if [ -f .env ]; then
export "$(grep -v '^#' .env | xargs)"
fi
# Functions
print_error() {
echo "${1}" >&2
}
print() {
echo "${1}"
}
check_requirements() {
requirements=("test" "which")
for requirement in "${requirements[@]}"; do
if ! command -v "${requirement}" &>/dev/null; then
print_error "Can not find ${requirement}. Please be sure ${requirement} is installed."
exit
fi
done
}
# $1 = question
# $2 = yes condition
promt_user() {
read -r -p "${1} " yn
case $yn in
[Yy]*)
"${@:2}"
return
;;
[Nn]*)
return
;;
*) print_error "Please answer yes or no." ;;
esac
}
: Help
if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
print "\
############################################################
Usage: ./${filename} [arg1] [arg2]
############################################################
This bash script is for ...
############################################################
"
exit
fi
: Main method
main() {
check_requirements
promt_user "Do you want to do this?" echo "yes I do"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment