如何设置一个变量作为数组的默认值? [英] How to set the default value of a variable as an array?

查看:407
本文介绍了如何设置一个变量作为数组的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现,有可能有击设置一个变量时变量未设置(如在<一个记载的默认值href=\"http://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash\">this帖子)。

不幸的是,这似乎并没有当默认值是一个数组工作。例如,考虑

  DEFAULT_VALUE =(0 1 2 3 4)my_variable = $ {my_variable:=($ {DEFAULT_VALUE [@​​]})}回声$ {my_variable [0]}
(0 2 3 4)#returns阵列:-(回声$ {my_variable [1])
#returns空

有谁知道如何做到这一点?请注意,更改:= : - 没有帮助

另一个问题是,无论解决方案,我们得到也应该工作的时候 my_variable 已经预先设置为好,这样

  my_variable =(ABC)
DEFAULT_VALUE =(0 1 2 3 4)my_variable = $ {my_variable:=($ {DEFAULT_VALUE [@​​]})}回声$ {my_variable [0]}
一个回声$ {my_variable [1]}
b的回声$ {my_variable [2]}
C


解决方案

要使它阵列中使用:

 取消设置my_variable DEFAULT_VALUE
DEFAULT_VALUE =(A B10)
my_variable =($ {my_variable [@]: - $ {DEFAULT_VALUE [@​​]}})printf的%S \\ n$ {my_variable [@]}
A b
10printf的%S \\ n$ {DEFAULT_VALUE [@​​]}
A b
10

在线演示

男人庆典

  $ {参数:-word}
   使用缺省值。如果参数没有设置或者为空,word的扩展将被替换。
   否则,参数的值被替换。

I recently discovered that it is possible to have Bash set the a variable to a default value when that variable is not set (as described in this post).

Unfortunately, this does not seem to work when the default value is an array. As an example consider,

default_value=(0 1 2 3 4)

my_variable=${my_variable:=("${default_value[@]}")}

echo ${my_variable[0]}
(0 a  2 3 4) #returns array :-(

echo ${my_variable[1])
#returns empty

Does anyone know how do this? Note that changing := to :- does not help.

Another issue is that whatever solution we get should also work for when my_variable already set beforehand as well, so that

my_variable=("a" "b" "c")
default_value=(0 1 2 3 4)

my_variable=${my_variable:=("${default_value[@]}")}

echo ${my_variable[0]}
"a" 

echo ${my_variable[1]}
"b" 

echo ${my_variable[2]}
"c" 

解决方案

To make it array use:

unset my_variable default_value
default_value=("a b" 10)
my_variable=( "${my_variable[@]:-"${default_value[@]}"}" )

printf "%s\n" "${my_variable[@]}"
a b
10

printf "%s\n" "${default_value[@]}"
a b
10

Online Demo

As per man bash:

${parameter:-word}
   Use Default Values. If parameter is unset or null, the expansion of word is substituted.
   Otherwise, the value of parameter is substituted.

这篇关于如何设置一个变量作为数组的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆