Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Array value in default value assignment

I'm trying to assign an array of three values to a variable if it hasn't been assigned yet with the line

: ${SEAFILE_MYSQL_DB_NAMES:=(ccnet-db seafile-db seahub-db)}

Unfortunately, echoing ${SEAFILE_MYSQL_DB_NAMES[@]} results in (ccnet-db seafile-db seahub-db) and ${SEAFILE_MYSQL_DB_NAMES[2]} prints nothing. It seems, the value has been interpreted as a string and not as an array. Is there any way I can make my script assign an array this way?

This problem occurs on a Debian Jessie with bash 4.3.30 (in a docker container if that matters). Interestingly, the same code works on Ubuntu 16.04 with bash version 4.3.42, where it is handled as an array as I would expect it.

like image 358
RikuXan Avatar asked Apr 27 '16 15:04

RikuXan


People also ask

What is the default value of arrays?

When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.

How do I set default variable in bash?

Sets VAR with the value of first argument, and if the argument is not set, DEFAULTVALUE is used. Notice the colon and dash characters. This little function starts a simple HTTP server that serves from current directory.


1 Answers

How about doing it in several stages? First declare the fallback array, then check if SEAFILE_MYSQL_DB_NAMES is set, and assign if needed.

DBS=(ccnet-db seafile-db seahub-db)
[[ -v SEAFILE_MYSQL_DB_NAMES ]] || read -ra SEAFILE_MYSQL_DB_NAMES <<< ${DBS[@]}

Based on this answer.

like image 80
dimid Avatar answered Oct 13 '22 20:10

dimid