根据 bash 脚本中的另一个变量名称创建对变量的引用?

根据 bash 脚本中的另一个变量名称创建对变量的引用?

假设我在 bash 脚本中有这些变量:

path_family="/home/family"
path_family_log="/var/log/family.log"
path_friends="/home/friends"
path_friends_log="/var/log/friends.log"
path_pets="/home/pets"
path_pets_log="/var/log/pets.log"

我想创建一个 for 循环,我可以在其中执行如下操作:

for TYPE in family friends pets
do
  for FILE in $path_<TYPE>
  do
    cat $FILE >> $path_<TYPE>_log
  done
done

显然这不是正确的代码,只是表达我想要的最直接的方式。我正在绞尽脑汁地试图找出如何对变量名称进行子字符串替换并使其按预期工作。

答案1

我建议改用关联数组:

#! /bin/bash -
typeset -A dir log # declare both variables as associative arrays
dir=(
   [family]=/home/family
  [friends]=/home/friends
     [pets]=/home/pets
)
log=(
   [family]=/var/log/family.log
  [friends]=/var/log/friends.log
     [pets]=/var/log/pets.log
)
for type in "${!dir[@]}"
do
  cat -- "${dir[$type]}/somefile" >> "${log[$type]}"
done

"${!array[@]}"是检索数组键列表的 ksh 语法(无特定顺序))。

或者在 zsh 中更清晰(它在 bash 之前几十年就已经有了关联数组):

#! /bin/zsh -
typeset -A dir log
dir=(
  family  /home/family
  friends /home/friends
  pets    /home/pets
)
log=(
  family  /var/log/family.log
  friends /var/log/friends.log
  pets    /var/log/pets.log
)
for type in ${(k)dir}
do
  cat -- $dir[$type]/somefile >> $log[$type]
done

使用 ksh93(bash 借用了它的关联数组语法),您还可以使用复合变量的关联数组:

#! /bin/ksh93 -
conf=(
   [family]=(dir=/home/family;  log=/var/log/family.log)
  [friends]=(dir=/home/friends; log=/var/log/friends.log)
     [pets]=(dir=/home/pets;    log=/var/log/pets.log)
)
for type in "${!conf[@]}"
do
  cat -- "${conf[$type].dir}/somefile" >> "${conf[$type].log}"
done

答案2

记住您提供的变量和下面的代码将实现您正在寻找的内容。我希望这可以帮助您和其他人现在和将来。

Bash 多行:

for TYPE in family friends pets 
do  
    for FILE in $(eval echo "\$path_$TYPE/*")
    do 
        cat $FILE >> $(eval echo "\$path_${TYPE}_log")
    done
done

单衬管

for TYPE in family friends pets ;do  for FILE in $(eval echo "\$path_$TYPE/*"); do cat $FILE >> $(eval echo "\$path_${TYPE}_log") ;done ; done

相关内容