Skip to content

Instantly share code, notes, and snippets.

@akutz
Last active September 25, 2015 20:36
Show Gist options
  • Save akutz/83358c0bcbcbe06b08a1 to your computer and use it in GitHub Desktop.
Save akutz/83358c0bcbcbe06b08a1 to your computer and use it in GitHub Desktop.
varsety
#!/bin/bash
# flag for debug logging
DEBUG=true
# store the args passed to this script, just in case
ARGS=$@
# mark this build with an epoch. this is also the only place in the
# file where it's necessary to use a subshell
EPOCH=$(date +%s)
########################################################################
## VARSETY ##
########################################################################
# the name of the pipe used in place of subshells
P=$HOME/.varsety-$EPOCH
# removes the pipe file
function rm_varsety() {
rm -f $P
}
# don't exit this script without cleaning up the pipe
trap rm_varsety SIGHUP SIGINT SIGKILL SIGTERM EXIT
# named pipe for assigning values to variables. this avoids the
# creation of multiple subshells to run commands, thereby increasing
# the speed of this script by literally dozens of seconds
mkfifo $P
# var is a shortcut for assigning the output of a command to an
# unexported variable.
#
# the function expects at least two arguments: the name of the variable
# and the command to execute from which to get output. the function
# also can take n-1 arguments to account for the command's possible
# arguments
#
# in the example below the echo statement will print "again" to the
# console because the var function will overwrite the value of the
# already-defined hello variable
#
# hello=world
# var hello again
# echo $hello
#
function var() {
n=$1 && shift && c=$@
if [[ $DEBUG = true ]]; then echo "varname=$n varcmd=$c "; fi
eval "{ $c; } > $P & { read -r $n < $P; }"
}
# same as var but ony sets value if var name is yet undefined.
#
# in the example below the echo statement will print "world" to the
# console because the zvar function did not override the
# already-defined hello variable
#
# hello=world
# zvar hello again
# echo $hello
#
function zvar() {
eval "if [[ -z \$$1 ]]; then var \$@; fi"
}
# VAR is a shortcut for assigning the output of a cmmand to an
# exported variable
#
# for more information on this function please see the function var
function VAR() {
var $@
eval "export $1=\$$1"
}
# same as VAR but ony sets value if var name is yet undefined
#
# # for more information on this function please see the function zvar
function ZVAR() {
eval "if [[ -z \$$1 ]]; then VAR \$@; export $1=\$$1; fi"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment