Some of my utils functions often share the exact same initial code, that allows the function to be called with an argument or piped input:
RED=$(tput setaf 1)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# -----------
function yellow {
local arg
if (( "$#" == 0 )); then
IFS= read -r arg
set -- "$arg"
fi
echo "${YELLOW}$1${RESET}"
}
function red {
local arg
if (( "$#" == 0 )); then
IFS= read -r arg
set -- "$arg"
fi
echo "${RED}$1${RESET}"
}
Is there a technique that allows me to "reuse" or somehow source the identical portion of code into the function definition? In my example this would be:
local arg
if (( "$#" == 0 )); then
IFS= read -r arg
set -- "$arg"
fi
source script_name.shor just. script_name.shbut be careful, script will be executed while sourcing