有没有办法在外壳脚本中动态获取 yaml 值



>我有一个像这样的yaml文件,

dev:
  host_place: "some place"
qa:
  host_place: "another place"

在 shell 脚本中,我正在尝试获取该值。如果我硬接线 dev 或 qa,这些值就会显示出来。但是,如果我将其作为输入参数,它不会显示任何内容。我的外壳脚本如下所示

#! /bin/bash
. yaml_par.sh
eval $(yaml_par config.yml "con_")
host=$con_dev_host_place
echo $host

如果我运行它,它将正常工作

但是如果我在下面进行修改,它将不起作用。

#! /bin/bash
. yaml_par.sh
envo=$1
eval $(yaml_par config.yml "con_")
host=$con_$envo_host_place
echo $host

可能是什么原因?

你的第二个例子并没有像你认为的那样扩展。

想想吧。你期望 shell 查看$con_$envo_host_place并意识到你的意思是让它扩展$envo以获得$con_dev_host_place然后扩展它以获得值。

外壳怎么会知道呢?

您可能认为您可以执行${con_${envo}_host_place}来强制解决问题,但这也不起作用。您只是从外壳中得到一个"错误的替换"错误。

但是,您可以进行间接外壳变量扩展。这在 Bash FAQ 006 中有介绍。

# Bash
realvariable=contents
ref=realvariable
echo "${!ref}"   # prints the contents of the real variable
# ksh93 / mksh / Bash 4.3
realvariable=contents
typeset -n ref=realvariable
echo "${!ref} = $ref"      # prints the name and contents of the real variable
# zsh
realvariable=contents
ref=realvariable
echo ${(P)ref}   # prints the contents of the real variable

对于 bash:如果变量中的值用于另一个变量名称,请使用eval获取该值:

eval host=$con_${envo}_host_place

最新更新