hi,
as far as i know there are 2 ways to pass input data to a bash function:
1) via standard input
Code:
func_name < data.txt
func_name <<< "${data}"
2) via positional parameters:
a. passing input data filename
Code:
func_name "data.txt"
b. passing the data variable
Code:
func_name "${data}"
c. passing the data var name and then declaring it by reference
Code:
function func_name () {
declare -n input_data=$1
...
}
func_name data
what is the best way to deal with all of these options, so that you can remember which input way should be used with each function you write?
would it be a good idea to write a helper function to detect the input type and pass it to the commands of the main function?
i mean something like this:
Code:
function main () {
declare input=$(__input_detect "$@")
cat ${input}
return 0
}
function __input_detect () {
# check if standard input is present
if read -t0; then
echo "< /dev/stdin"
return 0
fi
[[ -z ${1+x} ]] \
&& retun 0
# check if $1 is a valid file name
if [[ -f $1 ]]; then
echo "$1"
# check if $1 is the name of an existing variable
elif [[ ! -z ${!1+x} ]]; then
echo "<<< \"${!1}\""
else
echo "<<< \"$1\""
fi
return 0
}
# all of these invocation ways should work:
main_func data.txt
main_func < data.txt
main_func <<< "${data}"
# and these should not (so far):
main_func "${data}"
main_func data
this example is only partially working, but i'm posting it just to let you understand what i mean...
do you think such an input detection is somehow useful, or is it just a waste of time?