Linux shell script to instantiate different mongod process

Connect with

shell script mongodb startShell script mongodb, shell script to spawn different mongod processes on different ports in a single system and add a replica set of MongoDB. This is very easy to do and write in Linux shell script instead of writing one by on Linux terminal.

Linux shell script to spawn mongod process

To understand this you must know the basic syntax of linux script. Our objective is to write a shell script which do on behalf of yours linux terminal stuff.

#!/bin/bash

course="M310"
exercise="HW-1.2"
workingDir="$HOME/${course}-${exercise}"
dbDir="$workingDir/db"
logName="mongo.log"

ports=(31120 31121 31122)
replSetName="TO_BE_SECURED"

host=`hostname`
initiateStr="rs.initiate({
                 _id: '$replSetName',
                 members: [
                  { _id: 1, host: '$host:31120' },
                  { _id: 2, host: '$host:31121' },
                  { _id: 3, host: '$host:31122' }
                 ]
                })"

# create working folder
mkdir -p "$workingDir/"{r0,r1,r2}

# launch mongod's
for ((i=0; i < ${#ports[@]}; i++))
do
  mongod --dbpath "$workingDir/r$i" --logpath "$workingDir/r$i/$logName.log" --port ${ports[$i]} --replSet $replSetName --fork
done

# wait for all the mongods to exit
sleep 3

# initiate the set
mongo --port ${ports[0]} --eval "$initiateStr"


Your suggestions are welcome to encourage writing. Happy learning 🙂


Connect with

1 thought on “Linux shell script to instantiate different mongod process”

  1. Pingback: ramesh

Leave a Comment

Your email address will not be published. Required fields are marked *