如何在 shell 脚本中动态生成新的变量名? [英] How can I generate new variable names on the fly in a shell script?

查看:134
本文介绍了如何在 shell 脚本中动态生成新的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 shell 脚本中生成动态 var 名称,以循环处理一组具有不同名称的文件,如下所示:

I'm trying to generate dynamic var names in a shell script to process a set of files with distinct names in a loop as follows:

#!/bin/bash

SAMPLE1='1-first.with.custom.name'
SAMPLE2='2-second.with.custom.name'

for (( i = 1; i <= 2; i++ ))
do
  echo SAMPLE{$i}
done

我希望输出:

1-first.with.custom.name
2-second.with.custom.name

但我得到了:

SAMPLE{1}
SAMPLE{2}

是否可以即时生成 var 名称?

Is it possible generate var names in the fly?

推荐答案

你需要利用可变间接:

SAMPLE1='1-first.with.custom.name'
SAMPLE2='2-second.with.custom.name'

for (( i = 1; i <= 2; i++ ))
do
   var="SAMPLE$i"
   echo ${!var}
done

来自 Bash 手册页,在参数扩展"下:

From the Bash man page, under 'Parameter Expansion':

"如果参数的第一个字符是感叹号(!),则引入了可变间接级别.Bash 使用的值由参数的其余部分形成的变量作为参数的名称多变的;然后扩展此变量,并在其余的替换,而不是参数本身的值.这称为间接扩展."

"If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion."

这篇关于如何在 shell 脚本中动态生成新的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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