Last active
May 29, 2024 00:11
-
-
Save RoboSparrow/77aba344c9519cd58a67c38fae33f666 to your computer and use it in GitHub Desktop.
Bash: checks if a variable has been set and is not empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
function pass { | |
echo -e "\033[0;32m[OK]\033[0m ${1}" | |
} | |
function fail { | |
echo -e "\033[0;31m[ERROR]\033[0m ${1}" | |
} | |
function require_var { | |
# checks if a variable has been set and is not empty | |
if [ -z "${!1+x}" ]; then | |
fail "Variable '${1}' does not exist" | |
return # exit 1 | |
fi | |
if [ -z "${!1}" ]; then | |
fail "Variable '${1}' ' is empty" | |
return # exit 1 | |
fi | |
pass "${1}=\"${!1}\"" | |
} | |
# -- tests --- | |
source_OK="I'm alive" | |
source_EMPTY= | |
require_var "source_OK" | |
require_var "source_EMPTY" | |
require_var "source1_NOPE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment