Last active
August 20, 2020 20:33
-
-
Save stephenmm/ea9782633382b860bd6c680c5a84d6ad to your computer and use it in GitHub Desktop.
Very simple named arguments for bash functions
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
# Do not use in public facing servers as I am sure it can do bad things by malicious individuals | |
# Initialize variables and functions | |
unset -f boo | |
unset -f echoerror | |
unset other | |
echoerr() { printf "%s\n" "$*" >&2; } | |
# Example bash function to show the use of: | |
# required args "rqrd_arg" | |
# named args "namd_arg" | |
# named args with defaults "namd_dflt" | |
# pass by reference return variable "rvar" | |
# Only uses STDOUT if no return variable provided | |
function boo() { | |
echoerr ARGS:$@ ;# Illustration purpose only REMOVETHISLINE | |
local rqrd_arg=$1; shift; [[ -z $rqrd_arg ]] && echoerr "ERROR: Missing required arg rqrd_arg" && return 1 | |
local namd_dflt=dflt ;# Define default argument | |
unset rvar ;# Prepare return value if provide | |
local $* ;# Evaluates named args. Ex: namd_dflt=4 | |
[[ -z $rvar ]] && echo "rqrd_arg:namd_dflt:namd_arg = $rqrd_arg:$namd_dflt:$namd_arg" || eval $rvar="'rqrd_arg:namd_dflt:namd_arg = $rqrd_arg:$namd_dflt:$namd_arg'" | |
} | |
# Test the function boo | |
export other | |
boo 1 namd_arg=2 namd_dflt=4; echo errorcode=$? other=$other | |
boo 1 namd_arg=2 invld_arg namd_dflt=4; echo errorcode=$? other=$other | |
boo 1 namd_arg=2 invld_arg ; echo errorcode=$? other=$other | |
boo ; echo errorcode=$? other=$other | |
boo 1 rvar=other ; echo errorcode=$? other=$other | |
# Other useful examples | |
# Can override the env variables by passing them in as named args: Xproj2generic <file> PROJ=trunk | |
function Xgenric2proj() { | |
# Help msg | |
if [[ $# -lt 1 ]] || [[ $1 == help ]]; then | |
echo " ${FUNCNAME[0]} requires filename. Ex:Xproj2generic ~/.vim/session/prj_testbench.sxn.vim" >&2 | |
return 1 | |
fi | |
file=$1; shift | |
local $*; # Evaluate/create named args Ex: this=that | |
sed -i.bak "s/\$PROJ/$PROJ/g" $file | |
sed -i.bak "s/\$USER/$USER/g" $file | |
sed -i.bak "s/\$WORKSPACE/$WORKSPACE/g" $file | |
} | |
# Can override the env variables by passing them in as named args: Xproj2generic <file> PROJ=trunk | |
function Xproj2generic() { | |
if [[ $# -lt 1 ]] || [[ $1 == help ]]; then | |
echo " ${FUNCNAME[0]} requires filename. Ex:Xgeneric2proj ~/.vim/session/prj_testbench.sxn.vim WORKSPACE=clean" >&2 | |
return 1 | |
fi | |
file=$1; shift | |
local $*; # Evaluate/create named args Ex: this=that | |
sed -i.bak "s/$PROJ/\$PROJ/g" $file | |
sed -i.bak "s/$USER/\$USER/g" $file | |
sed -i.bak "s/$WORKSPACE/\$WORKSPACE/g" $file | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment