Skip to content

Instantly share code, notes, and snippets.

@Pelirrojo
Last active June 23, 2020 15:30
Show Gist options
  • Save Pelirrojo/8f73e2cee3f07c6cf60f0177889e89f4 to your computer and use it in GitHub Desktop.
Save Pelirrojo/8f73e2cee3f07c6cf60f0177889e89f4 to your computer and use it in GitHub Desktop.
Base Template in Shell script for any typical automated instruction on Linux/MacOs
#!/usr/bin/env bash
# A base script to copy & paste typical bash script actions
# You can also use some better like: https://devhints.io/bash
# DO WHAT THE F*CK YOU WANT TO PUBLIC LICENSE #
# Version 2, December 2004 #
# #
# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> #
# #
# Everyone is permitted to copy and distribute verbatim or modified #
# copies of this license document, and changing it is allowed as long #
# as the name is changed. #
# #
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE #
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION #
# #
# 0. You just DO WHAT THE FUCK YOU WANT TO. #
# Function to check the command executed was ok or cut the execution with a message
function check {
if [ "$1" -ne 0 ]; then
echo "\n¯\_(ツ)_/¯ Problem running script. Please check errors. ¯\_(ツ)_/¯\n"
exit "$1"
fi
}
# Function to manage optional flags
BUILD_FLAG=true
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-d | --deploy )
echo "Running with --deploy option (by default)"
BUILD_FLAG=true
;;
-nd | -n |--no-deploy )
echo "Running with --no-deploy option"
BUILD_FLAG=false
;;
-h | --help )
echo "\nDeploy script usage:"
echo "--------------------------"
echo "All the flags are optional, and by default the code its uploaded."
echo "-d | --deploy => Deploy and upload the code to S3 and also upload the IaC stack"
echo "-nd | --no-deploy => Don't deploy the code to S3, but upload the IaC stack"
echo "-h | --help => Print this usage help\n"
exit 0
;;
*) echo 'Wrong parameter' >&2
exit 1
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
export BUILD_FLAG
if [ "$BUILD_FLAG" = true ] ; then
echo "Something happen..."
fi
# 1. Check dependencies
bash --version >/dev/null 2>&1 || { echo >&2 "I require Bash Shell but it's not installed. ¯\_(ツ)_/¯ Aborting."; exit 1; }
# 2. Read a var by keyboard
read -p 'Define a value for $VAR? ' VAR
echo "VAR="$VAR
# 3. Generate an "unique" timestamp enought to file generated in each second
echo "This a timestao for your log> "$(date +'%Y%m%d%H%M%S')
# 4. Test the result of a function:
#false # Uncomment this to test function error message
true # Uncomment this to ok behaviour (no message)
check $?
# 5. Ask user if continue with something dangerous:
read -r -p "This script is going to make some dangerous i.e. list current directory. Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
then
ls
fi
echo "\n▂▃▅▇█▓▒░ Mission Accomplished ░▒▓█▇▅▃▂\n"
# EOF :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment