加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 使用’.’的Bash脚本属性文件在变量名称中

发布时间:2020-12-14 02:09:48 所属栏目:Linux 来源:网络整理
导读:我是bash脚本的新手,对于在bash脚本中使用.properties文件中的属性有疑问. 我见过一个使用’.’的bash属性文件.变量名之间,例如: this.prop.one=someProperty 我看到他们在一个脚本中调用,如: echo ${this.prop.one} 但是当我尝试设置此属性时,我收到一个
我是bash脚本的新手,对于在bash脚本中使用.properties文件中的属性有疑问.

我见过一个使用’.’的bash属性文件.变量名之间,例如:

this.prop.one=someProperty

我看到他们在一个脚本中调用,如:

echo ${this.prop.one}

但是当我尝试设置此属性时,我收到一个错误:

./test.sh: line 5: ${this.prop.one}: bad substitution

如果我没有’,’我可以使用属性.在变量名中,并包含props文件:

#!/bin/bash
. test.properties
echo ${this_prop_one}

我真的希望能够使用’.’在变量名中,如果可能的话,不必包含.脚本中的test.properties.

这可能吗?

更新:

谢谢你的回答!那么,这很奇怪.我正在使用一个看起来像这样的bash脚本(glassfish服务):

#!/bin/bash

start() {
        sudo ${glassfish.home.dir}/bin/asadmin start-domain domain1
}

...

…还有像这样的属性文件(build.properties):

# glassfish
glassfish.version=2.1
glassfish.home.dir=${app.install.dir}/${glassfish.target}
...

那么,必须有一些方法来做到这一点吗?如果它们在属性文件中声明,这些可能不被视为“变量”吗?再次感谢.

解决方法

将它们加载到关联数组中.这将要求你的shell是bash 4.x,而不是/ bin / sh(即使是bash的符号链接,也在POSIX兼容模式下运行).

declare -A props
while read -r; do
  [[ $REPLY = *=* ]] || continue
  props[${REPLY%%=*}]=${REPLY#*=}
done <input-file.properties

…之后您可以像这样访问它们:

echo "${props[this.prop.name]}"

如果你想以递归的方式查找引用,那么它会变得更有趣.

getProp__property_re='[$][{]([[:alnum:].]+)[}]'
getProp() {
  declare -A seen=( ) # to prevent endless recursion
  declare propName=$1
  declare value=${props[$propName]}
  while [[ $value =~ $getProp__property_re ]]; do
    nestedProp=${BASH_REMATCH[1]}
    if [[ ${seen[$nestedProp]} ]]; then
      echo "ERROR: Recursive definition encountered looking up $propName" >&2
      return 1
    fi
    value=${value//${BASH_REMATCH[0]}/${props[$nestedProp]}}
  done
  printf '%sn' "$value"
}

如果我们有如下定义的道具(你也可以通过使用适当的input-file.properties在这个答案的顶部运行循环来获得):

declare -A props=(
  [glassfish.home.dir]='${app.install.dir}/${glassfish.target}'
  [app.install.dir]=/install
  [glassfish.target]=target
)

……然后行为如下:

bash4-4.4$getProp glassfish.home.dir
/install/target

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读