Linux shell script to instantiate different mongod process

Connect with

MongoDB
How to write a shell script so that you can spawn different mongod process on different post in single system and add 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 Reply

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