Skip to content

Instantly share code, notes, and snippets.

@forestbaker
Last active December 5, 2015 09:05
Show Gist options
  • Save forestbaker/c8fa079880359aeb59c8 to your computer and use it in GitHub Desktop.
Save forestbaker/c8fa079880359aeb59c8 to your computer and use it in GitHub Desktop.
Collapsing Function Examples and More!
#!/usr/bin/env bash
# From Bash Hackers - http://wiki.bash-hackers.org/howto/collapsing_functions
# The first time you run chatter(), the function redefines itself based on the value of verbose. Thereafter, chatter doesn't check $verbose, it simply is.
# Further calls to the function reflect its collapsed nature.
# If verbose is unset, chatter will echo nothing, with no extra effort from the developer.
[[ $1 = -v || $1 = --verbose ]] && verbose=1
chatter() {
if [[ $verbose ]]; then
chatter() {
echo "$@"
}
chatter "$@"
else
chatter() {
:
}
fi
}
echo "Waiting for 10 seconds."
for i in {1..10}; do
chatter "$i"
sleep 1
done
#2
if ! type _get_comp_words_by_ref >/dev/null 2>&1; then
_get_comp_words_by_ref ()
{
echo booyah
}
#!/usr/bin/env bash
# A collapsing function that enables or disables logging
# enable with 1 / disable with 0 (or anything else ;-)
declare -r LOG_ENABLE='1'
# TODO - something aint right with the date/time - "invalid number"
[[ 1 = $LOG_ENABLE ]] && declare -r logit='printf "%(%Y%m%d-%H:%M:%S)T %s\n" -1' || declare -r logit=':'
# Use $logit instead of printf / echo
$logit "This is where the magic begins"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment