I am complementary on @ Ikehah's (accepted) and @kevinarpe's (also good) answers.
You can do "${arr[@]:+${arr[@]}}" to get around the problem. The right-hand side (i.e. after :+ ) provides an expression that will be used if the left-hand side is undefined / empty.
The syntax is secret. Please note that the right side of the expression will undergo parameter expansion, so special attention should be paid to the presence of consecutive quotes.
: example copy arr into arr_copy arr=( "1 2" "3" ) arr_copy=( "${arr[@]:+${arr[@]}}" )
As @kevinarpe mentions, a less cryptic syntax is to use the ${arr[@]:0} array slice notation (in Bash versions >= 4.4 ), which extends to all parameters starting at index 0. This also doesn't require so much repetitions. This extension works regardless of set -u , so you can always use it. The man page says (under the options extension ):
${parameter:offset}
${parameter:offset:length}
... If the parameter is an indexed array name signed with the @ or * character, the result is the length of the array element starting with ${parameter[offset]} . A negative offset is taken relative to one that exceeds the maximum index of the specified array. This is an extension error if the length is zero.
This is an example provided by @kevinarpe, with alternative formatting to put the output as evidence:
set -u function count() { echo $# ; }; ( count xyz ) : prints "3" ( arr=() count "${arr[@]}" ) : prints "-bash: arr[@]: unbound variable" ( arr=() count "${arr[@]:0}" ) : prints "0" ( arr=(xyz) count "${arr[@]:0}" ) : prints "3"
This behavior is dependent on the version of Bash. You may also have noticed that the operator of length ${#arr[@]} will always be set to 0 for empty arrays, regardless of set -u , without causing an βunbound variable errorβ.
init_js Mar 13 '18 at 20:15 2018-03-13 20:15
source share