1

这是我目前的流程:

var[product]=messaging_app
var[component]=sms
var[version]=1.0.7
var[yum_location]=$product/$component/$deliverable_name
var[deliverable_name]=$product-$component-$version

# iterate on associative array indices
for default_var in "${!var[@]}" ; do

  # skip variables that have been previously declared
  if [[ -z ${!default_var} ]] ; then

    # export each index as a variable, setting value to the value for that index in the array
    export "$default_var=${var[$default_var]}"
  fi
done

我正在寻找的核心功能是设置一个不会覆盖先前声明的变量的默认变量列表。

上面的代码做到了这一点,但它也造成了这些变量现在不能相互依赖的问题。这是因为关联数组的索引输出"${!var[@]}"的顺序并不总是与它们声明的顺序相同。

是否存在更简单的解决方案,例如:

declare --nooverwrite this=that

我还没有找到类似的东西。

另外,我知道这可以通过 if 语句来完成。但是,使用一堆 if 语句会破坏具有近 100 个默认变量的脚本的可读性。

4

1 回答 1

1

3.5.3 外壳参数扩展

${参数:=字}

如果参数未设置或为空,则将单词的扩展分配给参数。然后替换参数的值。不能以这种方式分配位置参数和特殊参数。

所以

: ${this:=that}

:需要,因为否则外壳将${this:=that}视为运行请求,作为命令,无论扩展为什么。

$ echo "$this"
$ : ${this:=that}
$ echo "$this"
that
$ this=foo
$ echo "$this"
foo
$ : ${this:=that}
$ echo "$this"
foo

如果这更适合情况,您也可以首先使用变量(而不是单独使用)(但请确保这很清楚,因为在以后的编辑中很容易搞砸)。

$ echo "$this"
$ echo "${this:=that}"
that
$ echo "$this"
that

但是,动态执行此操作不太容易,并且可能需要eval.

于 2015-01-23T20:34:37.263 回答