Mongodump fails when run in bash script

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

The error message is inconsistent with what you are doing in the script.

The error message is about localhost:27017 but you are specifying mongodb1,2,3 in your script.

I suppose I forgot to include my question :slight_smile: :
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”) ?

Yes, I noticed that. Don’t know why, though.

I suspect your $password brakes the parsing of the mongodump line due to special characters.

I suggest that you put mongodb:…replicatSet=rs0 between double quotes to make sure that the URI is a single argument.

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.

1 Like

Forgot to say: Thank you for helping out!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.