Skip to content

Instantly share code, notes, and snippets.

@mohanpedala
Last active July 25, 2018 23:00
Show Gist options
  • Save mohanpedala/993c724a6f04459ce0e0e9deae79b4db to your computer and use it in GitHub Desktop.
Save mohanpedala/993c724a6f04459ce0e0e9deae79b4db to your computer and use it in GitHub Desktop.
Bash Script best practice
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail

# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "INFO : __dir is ${__dir}"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
echo "INFO : __file is ${__file}"
__base="$(basename ${__file} .sh)"
echo "INFO : __base is ${__base}"

#__root of the project depends on the location of this script in the folder structure
__root="$(cd "$(dirname "$(dirname "${__dir}")")" && pwd)"
echo "INFO : __root is ${__root}"

for library_module in ${__dir}/library/*; do
   source ${library_module}
done

Explanation

  • set: set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.

  • -o: option-name: Set the option corresponding to option-name:

  • errexit: Same as -e.

  • pipefail: If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

Reference Click Here

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