Bash脚本属性文件使用'.' 在变量名称中

Mat*_*att 5 linux bash scripting properties-file

我是bash脚本的新手,对于在bash脚本中使用.properties文件中的属性有疑问.

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

this.prop.one=someProperty
Run Code Online (Sandbox Code Playgroud)

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

echo ${this.prop.one}
Run Code Online (Sandbox Code Playgroud)

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

./test.sh: line 5: ${this.prop.one}: bad substitution
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/bash
. test.properties
echo ${this_prop_one}
Run Code Online (Sandbox Code Playgroud)

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

这可能吗?

更新:

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

#!/bin/bash

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

...
Run Code Online (Sandbox Code Playgroud)

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

# glassfish
glassfish.version=2.1
glassfish.home.dir=${app.install.dir}/${glassfish.target}
...
Run Code Online (Sandbox Code Playgroud)

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

Cha*_*ffy 9

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

declare -A props
while read -r; do
  [[ $REPLY = *=* ]] || continue
  props[${REPLY%%=*}]=${REPLY#*=}
done <input-file.properties
Run Code Online (Sandbox Code Playgroud)

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

echo "${props[this.prop.name]}"
Run Code Online (Sandbox Code Playgroud)

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

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 '%s\n' "$value"
}
Run Code Online (Sandbox Code Playgroud)

如果我们已经props定义如下(你也可以通过在适当的时候在这个答案的顶部运行循环来获得input-file.properties):

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

......然后行为如下:

bash4-4.4$ getProp glassfish.home.dir
/install/target
Run Code Online (Sandbox Code Playgroud)