【问题标题】:Declaring variables with indirect reference with a prefix用前缀间接引用声明变量
【发布时间】:2020-08-11 17:48:55
【问题描述】:

我将我的参数存储在一个文件中,并使用前缀调用它们,我得到它有输入。现在,我正在获取输入并为其添加前缀并将其存储为新变量,然后将我的新变量间接指向我的实际变量以在我的脚本中使用。

有没有办法直接提到指向我的主变量的间接变量指针,比如 value1=$(!$pk_value1) 这样的东西,这样我就可以跳过新的变量声明。我要声明近 10 个变量,这使我的代码很长。

我当前的代码:

source values.sh
read -p "Enter Identifier : " pk

value1here=${pk}_value1
value2here=${pk}_value2
value3here=${pk}_value3

value1=${!value1here}
value2=${!value2here}
value3=${!value3here}

values.sh(我在这里声明了近 300 个变量)

p1_value1=name1
p1_value2=host1
p1_value3=user1

p2_value1=name2
p2_value2=host2
p2_value3=user2

有没有办法直接提到间接变量指针+我的名字像 value1=$(!$pk_value1) 这样的东西,这样我就可以跳过新的变量声明。我要声明近 10 个变量,这使我的代码很长。

【问题讨论】:

  • 使用关联数组怎么样?

标签: linux bash shell variables unix


【解决方案1】:

如果您的 Bash 足够新,则使用 -n 间接变量属性,如下所示:

#!/usr/bin/env bash

source values.sh
read -r -p 'Enter Identifier : ' pk

declare -n \
  value1="${pk}_value1" \
  value2="${pk}_value2" \
  value3="${pk}_value3"

从文件values.sh 填充关联数组的替代方法:

#!/usr/bin/env bash

declare -A values="($(
  xargs -l1 \
    bash -c \
    'IFS="=" read -r k v <<<"$@"; printf "[%q]=%q\n" "$k" "$v"' _ \
    <values.sh
))"

read -r -p 'Enter Identifier : ' pk

declare -- \
  value1="${values[${pk}_value1]}" \
  value2="${values[${pk}_value2]}" \
  value3="${values[${pk}_value3]}"

关联数组群体的工作:

xargs -l1 会将stdio 输入流的行(此处为:&lt;values.sh)转换为命令的参数。

xargs调用的命令是bash -c,女巫执行这里详述的内联脚本:

# Read variables k and v from the arguments
# streamed as a here-string <<<"",
# using the = sign as the Internal Field Separator.
# Actually splitting key=value into k and v.
IFS="=" read -r k v <<<"$@"

# Format variables k and v into an Associative array
# entry declaration in the form [key]=value,
# with %q adding quotes or escaping if required.
printf "[%q]=%q\n" "$k" "$v"

最后,关联数组声明和赋值declare -A values="($(commands))" 获取由xarg 和内联shell 脚本commands 生成的条目。

【讨论】:

  • 非常好,来自man bash 的与创建nameref 相关的文本是“可以使用-n 选项为变量分配nameref 属性以...创建@ 987654338@,或对另一个变量的引用。”如果你想包括参考。
  • 我使用了 declare -n ,但我收到此错误。/tstnew.sh:第 16 行:声明:-n:无效选项声明:用法:声明 [-aAfFgilrtux] [-p] [名称[=值] ...]
  • @Lea 我也尝试过另一种方法,只有标识符被打印出来,而值没有被打印出来。
  • 它的工作非常感谢你:) 如果你能给我上面使用的数组的解释,你能找到吗?
  • @Rajesh 我添加了关联数组填充过程的详细说明。
猜你喜欢
  • 2016-02-01
  • 2018-02-06
  • 1970-01-01
  • 2023-01-28
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多