When I run mongodump command in shell script, it works fine, however when I run the exact same command in a bash script, it fails to connect to the MongoDB replica set and returns this error:
2021-12-28T13:08:50.896+0100 Failed: can't create session: could not connect to server: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: localhost:27017, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp [::1]:27017: connect: connection refused }, ] }
Here is the script I’m using:
#!/bin/bash
# including error handling
script_path="$( cd -- "$(dirname "$0")">/dev/null 2>&1 ; pwd -P )"
source $script_path/scriptfail_notifier.sh
# (1) set up mongodump variables
now() {
date +%Y-%m-%dT%H:%M
}
password="<redacted>"
# (2) remove dbdumps created more than 7 days ago from backup directory
echo "removing dbdumps created more than 7 days ago"
find /dbdump/mongodb/* -type d -ctime +7 | xargs rm -rf 2>&1
# (3) do the mongo database backups (dumps)
echo "mongodump started"
mongodump mongodb://mongo_backup:$password@mongodb1,mongodb2,mongodb3/?replicaSet=rs0 --out=/dbdump/mongodb/mongodb_$(now) --oplog 2>&1
echo "mongodump completed"
exit 0
I suppose I forgot to include my question :
Why is my mongodump script failing when declaring as #!/bin/bash, but then works fine with !#/bin/sh (apart from error handling part, which returns “: set: Illegal option -o pipefail”) ?
No special chars in the password, but simply sticking the mongodump command between double quotes did the trick. Now I feel a bit embarrassed that it was such a simple thing ^^
I guess I need to get a better understanding of these subtle differences between shell and bash scripting.