在bash中,是否有一种方法可以在变量中替代或嵌套变量? [英] In bash, is there a way to substitue or nest a variable within a variable?

查看:58
本文介绍了在bash中,是否有一种方法可以在变量中替代或嵌套变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个变量;

var_one_string=foo
var_two_string=bar

我将如何完成类似的工作(伪代码示例);

How would I accomplish something like this (pseudo code examples);

示例1

for i in one two; do
  echo $var_${i}_string
done
# Desired output
foo
bar

示例2

for i in one two; do
  echo $var_$(echo ${i})_string
done
# Desired output
foo
bar

我知道这是错误的替换,我只是想知道是否有一种方法可以将字符串嵌套在另一个变量调用中?

I understand that this is bad substitution, I am just wondering if there is a way to nest a string within another variable call?

我能够使它正常工作

var_one_string=foo
var_two_string=bar

for i in $(echo ${!var_*}); do
    echo ${!i}
done
foo
bar

推荐答案

使用内置的 declare 以及 bash 中的间接变量扩展.首先,将数组中具有动态性质的元素定义为

Use the declare built-in along with indirect-variable expansion in bash. First define the elements of for the dynamic nature in an array as

#!/bin/bash

list=(one two)
unset count

for var in "${list[@]}"; do 
    declare var_${var}_string="string"$((++count))
done

现在使用间接扩展访问创建的变量

and now access the created variables using indirect expansion

for var in "${list[@]}"; do 
    dymv="var_${var}_string"
    echo "${!dymv}"
done

,切勿为此要求使用 eval .由于使用有害命令不太可能注入代码,因此可能很危险.

and never use eval for this requirement. Could be dangerous because of unlikely code-injection possibility with a harmful command.

这篇关于在bash中,是否有一种方法可以在变量中替代或嵌套变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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