Can somebody explain me, why the return value of a bash function is always echoed in the function and then consumed by my_var=$(my_func arg1 arg2 ..)
, when i look through code examples.
my_func ()
{
echo "$1 , $2, $3"
}
my_var=$(my_func .. .. ..);
instead of using this, which would not open a subshell
declare g_RV #-- global return value for all functions
myfunc ()
{
g_RV="$1 , $2, $3"
}
myfunc .. .. ..; my_var=$g_RV;
because i use the second way, and wonder, if this would fail against the first method in some cases. There must be a cause, because everyone is opening a subshell.
EDIT: because of Kusalananda and Paul_Pedant comments
I added a recursive function call with g_RV - LAF function , list all files of a directory $1, or do it recursive if $2 INT>0
and then function calls inside a function to other functions (look at sum functions!
declare g_RV
shopt -s dotglob nullglob
#-- Recursive call with g_RV
#---------------------------
#-- call: LAF [directory STR] [recursive INT (>0 .. true, 0 .. false)] ... List all files in a folder or inclusive all files in subfolders (recursive
LAF ()
{
local file files="" dir_path=$1
if [[ ${dir_path:0:1} != "/" ]]; then dir_path=$(readlink -f "$dir_path"); fi
for file in "$dir_path/"*; do
if [[ -d $file ]]; then (($2)) && { LAF "$file"; files+=$g_RV; } #-- recursive call
else files+="${file}"$'\n'; fi
done
g_RV=$files
}
LAF "/tmp" 1; my_var1=$g_RV; echo "$my_var1";
#-- function calling other functions with g_RV
#---------------------------------------------
sum_A ()
{
g_RV=$(($1+$2))
}
sum_B()
{
g_RV=$(($1+$2))
}
sum_C ()
{
local -i sum=0;
sum_A 5 6; sum+=$g_RV
sum_B 12 18; sum+=$g_RV
g_RV=$sum
}
sum_C; my_var2=$g_RV; echo "sum: $my_var2";