I want to assign the output of a mongo command (i.e database names) to a bash array variable but I am not sure how to go about it.
I am getting an error :
dump.sh
Starting-BACKUP
dump.sh
./dump.sh: line 16: declare: `–a': not a valid identifier
./dump.sh: line 24: mongo: command not found
Database backup was successful
when I attempt using dump.sh below:
#!/bin/bash
declare –a databases=()
databases=$(mongo --quiet --uri="mongodb://root:mypassword@mongodb-prom/admin" --authenticationDatabase admin --eval="show dbs;" | cut -d " " --field 1)
echo $databases
Ordinarily I am able to get a listing of the databases when I kubectl into the pod with following steps :
$ kubectl exec -it mongodb-prom-xxxxxxxxx-dddx4 -- sh
$ mongo
> use admin
> db.auth('root','mypassword')
> show dbs
admin 0.000GB
platforms 0.000GB
users 0.000GB
I am not sure why the mongo command is not being recognized because the same script is able to execute the mongodump command below :
mongodump --uri="<uri_here>" --authenticationDatabase admin --gzip --archive=/tmp/"<variable_here>".gz
UPDATE : This is the associated Dockerfile. My expectation is that both mongo and mongodump should be working by default in a mongo container but it seems only mongodump is working for now
FROM mongo
WORKDIR /opt/backup/
WORKDIR /usr/src/configs
COPY dump.sh .
RUN chmod x dump.sh
My two issues :
- Is my syntax correct for the variable assignment (I suspect its not correct) ?
- How should I properly declare the array variable to avoid the warnings ?
NB : Mongo tooling is already installed on the container and is actually working for mongodump
CodePudding user response:
You don't need declare -a
. Simply putting the value inside ()
in the assignment will make it an array.
To get all the elements of an array, you have to use ${variable[@]}
. $variable
is equivalent to ${variable[0]}
and just retrieves the first element.
databases=($(mongo --quiet --uri="mongodb://root:mypassword@mongodb-prom/admin" --authenticationDatabase admin --eval="show dbs;" | cut -d " " --field 1))
echo "${databases[@]}"
CodePudding user response:
With bashv4 , mapfile
is available, with Process Substitution.
mapfile -t databases < <(mongo --quiet --uri="mongodb://root:mypassword@mongodb-prom/admin" --authenticationDatabase admin --eval="show dbs;" | cut -d " " --field 1)
Now check the value of the databases array
declare -p databases
Your code has
declare -a databases=()
but
databases=$(...)
is not an array, the $(...)
construct is Command Substitution.
See also Bash Arrays