bash嵌套变量for循环 [英] bash nested variable in for loop

查看:134
本文介绍了bash嵌套变量for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到以下几点?


$ b

 #!/ bin / bash -x 

IPFILE_LIST =(
/ copytest / test1
/copytest/test2/test.conf
/ copytest / test3 / test3 / test3
/ copytest / test4 / test4


CopyFunction(){
for i in$ {$ 1 [@]};做
rsync -R $ 2 $ 3
完成
}

CopyFunction'IPFILE_LIST'$ i copytestdest

函数最终看起来像这样

  CopyFunction(){
for i in$ {IPFILE_LIST [@]};做
rsync -R $ i / copytestdest /
完成
}

它会执行rsync数组中的每个项目,最后我会得到以下输出:

copytestdest / copytest / test1
copytest / test2 / test.conf
copytestdest / copytest / test3 / test3 / test3
copytestdest / copytest / test4 / test4



如果可能的话,我也希望支持同样的功能,否则它可能需要另一个功能

CopyFunction copytestdest'IPFILE_LIST'

解决方案

在bash 4.3或更新版本中:
$ {$ arr [@]



$ b $ };做
rsync -R$ i$ 2
完成
}

如果没有现代的bash,你需要用 eval 来转向hackery:

  CopyFunction(){
local -a arr
local eval_cmd i

printf -v eval_cmd'arr =($ {%q [@]}) '$ 1
eval$ eval_cmd

为$ {arr [@]}中的i;做
rsync -R$ i$ 2
完成
}

其中任何一个都可以调用该函数:

  CopyFunction'IPFILE_LIST'copytestdest 






请注意,在这两种情况下 声明为本地变量 i 。因为它是本地的,所以它的值不会跳过函数调用,所以它没有任何副作用 - 它在函数退出后不再被定义。因为它是无副作用的,所以从函数外部控制它的名字没有任何意义,因此没有必要从外部传递这个名字。


Is there a way to do the follow below?

#!/bin/bash -x

IPFILE_LIST=(
  /copytest/test1
  /copytest/test2/test.conf
  /copytest/test3/test3/test3
  /copytest/test4/test4
)

CopyFunction() {
  for i in "${$1[@]}"; do
    rsync -R $2 $3
  done
}

CopyFunction 'IPFILE_LIST' $i copytestdest

Where the function would look like this in the end

CopyFunction() {
   for i in "${IPFILE_LIST[@]}"; do
      rsync -R $i /copytestdest/
   done
}

And it would execute each item in the array for rsync, in the end i should get an output of the following

copytestdest/copytest/test1 copytest/test2/test.conf copytestdest/copytest/test3/test3/test3 copytestdest/copytest/test4/test4

I would also like to support the follow in the same fuction if possible otherwise it will likely need to be another fuction

CopyFunction copytestdest 'IPFILE_LIST'

解决方案

In bash 4.3 or newer:

CopyFunction() {
  local -n arr=$1
  local i
  for i in "${arr[@]}"; do
    rsync -R "$i" "$2"
  done
}

Without modern bash, you need to turn to hackery with eval:

CopyFunction() {
  local -a arr
  local eval_cmd i

  printf -v eval_cmd 'arr=( "${%q[@]}" )' "$1"
  eval "$eval_cmd"

  for i in "${arr[@]}"; do
    rsync -R "$i" "$2"
  done
}

With either of these, the function can be called as:

CopyFunction 'IPFILE_LIST' copytestdest


Note that in both cases best practice has the variable i declared as local. Because it's local, its value doesn't escape the function call, so there aren't any side effects to its use -- it's no longer defined after the function exits. Because it's side-effect-free, there's no point whatsoever to controlling its name from outside the function, and thus no point to passing that name in from outside.

这篇关于bash嵌套变量for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆