小编mac*_*yle的帖子

如何对 bash 函数中的参数使用按引用调用

我试图将“var name”传递给函数,让函数转换具有此类“var name”的变量包含的值,然后能够通过其原始“var name”引用转换后的对象。

例如,假设我有一个将分隔列表转换为数组的函数,并且我有一个名为“animal_list”的分隔列表。我想通过将列表名称传递给函数,然后将 now 数组引用为“animal_list”来将该列表转换为数组。

代码示例:

function delim_to_array() {
  local list=$1
  local delim=$2
  local oifs=$IFS;

  IFS="$delim";
  temp_array=($list);
  IFS=$oifs;

  # Now I have the list converted to an array but it's 
  # named temp_array. I want to reference it by its 
  # original name.
}

# ----------------------------------------------------

animal_list="anaconda, bison, cougar, dingo"
delim_to_array ${animal_list} ","

# After this point I want to be able to deal with animal_name as an array.
for animal in "${animal_list[@]}"; do 
  echo "NAME: $animal"
done …
Run Code Online (Sandbox Code Playgroud)

bash shell-script function variable

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

bash ×1

function ×1

shell-script ×1

variable ×1