Bash Helper Functions

(, en)

Frequently used in CI/CD pipelines:

to_lower() {
  tr '[:upper:]' '[:lower:]'
}

to_upper() {
  tr '[:lower:]' '[:upper:]'
}

to_alnum() {
  tr -dc '[:alnum:]'
}

snake_uc_to_camel() {
  to_lower | sed -r 's/_([a-z0-9])/\U\1/g'
}

camel_to_snake_uc() {
  sed 's/\([a-z0-9]\)\([A-Z]\)/\1_\2/g' | to_upper
}

confirm() {
  # https://stackoverflow.com/questions/1885525/how-do-i-prompt-a-user-for-confirmation-in-bash-script
  read -p "${1:-Are you sure?} (y/n) " -n 1 -r
  echo    # (optional) move to a new line
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    return 0
  fi
  return 1
}

confirm_or_exit() {
  if ! confirm "$@"; then
    exit 0
  fi
}

check_env_var_presence() {
  : "${VARIABLE1?'not set'}"
  : "${VARIABLE2?'not set'}"

  if [[ ! "$ENV" =~ ^(dev|acc|prd)$ ]]; then
    echo "ENV needs to be one of dev, acc or prd, but not $ENV"
    exit 1
  fi
}

GIT_COMMIT_SHA="e4637392ae6a3fad3ec16d1e5a9b40657990d76b"
GIT_COMMIT_SHA_SHORT=${GIT_COMMIT_SHA:0:7}