my_var=$(my_func arg1 arg2 ..)
有人可以解释一下,当我查看代码示例时,为什么 bash 函数的返回值总是在函数中回显,然后由 消耗。
my_func ()
{
echo "$1 , $2, $3"
}
my_var=$(my_func .. .. ..);
而不是使用这个,它不会打开子shell
declare g_RV #-- global return value for all functions
myfunc ()
{
g_RV="$1 , $2, $3"
}
myfunc .. .. ..; my_var=$g_RV;
因为我使用第二种方法,并且想知道在某些情况下这是否会对第一种方法失败。肯定是有原因的,因为大家都在打开一个subshell。
编辑:由于 Kusalananda 和 Paul_Pedant 评论,
我添加了一个带有 g_RV - LAF function 的递归函数调用,列出目录 $1 的所有文件,或者如果 $2 INT>0 则递归,
然后在函数内部调用其他函数(查看求和函数!
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";