0

I want to start mongod with dbpath option as below

mongod --dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet rs0

Here is the mongod.service:-

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /etc/mongod.conf"
ExecStart=/usr/bin/mongod $OPTIONS
ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb
ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb

How to add --dbpath and --replSet option in ExecStart on mongod.service file using shell script.

I want my output look like below:-

mongod.service:-

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /etc/mongod.conf"
ExecStart=/usr/bin/mongod $OPTIONS --dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet rs0
ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb
ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb

I know to add some text at the end of line using below command:

sed '/ExecStart/s/$/ test/' mongod.service

Don't know how to add what I mentioned above as it contains hyphen, slash, etc.

Inian
  • 80,270
  • 14
  • 142
  • 161
Galet
  • 5,853
  • 21
  • 82
  • 148
  • What did you try for yourself? – Inian Mar 29 '18 at 09:42
  • I know to add some text at the end of line like "sed '/ExecStart/s/$/ test/' mongod.service " . Don't know how to add what I mentioned above as it contains hyphen, slash, etc. – Galet Mar 29 '18 at 09:45
  • Add it to the question! @karan – Inian Mar 29 '18 at 09:46
  • Updated the question – Galet Mar 29 '18 at 09:47
  • 1
    Since the service `$OPTIONS` already contains the path to a config file (`/etc/mongod.conf`), a more correct way to approach your changes would be to set the [`storage.dbPath`](https://docs.mongodb.com/manual/reference/configuration-options/#storage.dbPath) and [`replication.replSetName`](https://docs.mongodb.com/manual/reference/configuration-options/#replication.replSetName) values in the `/etc/mongod.conf` config file. Any manual changes to the `mongod.service` file may not be preserved between upgrades or reinstalls; the config file will be. – Stennie Mar 29 '18 at 09:55

1 Answers1

1

Your idea of using sed is right, but since the replace part contains / it should be escaped or separate separators need to be used for sed. Also double-quoting the sed expression would allow you to easily preserve the spaces. But need to ensure there is no $ expressions in the replace path.

sed "/^ExecStart=/s/$/ --dbpath \/var\/lib\/mongo\/ --config \/etc\/mongod.conf --replSet rs0/" file

Also could be done with awk by incrementing a column count by 1 and filling this in the last column

awk -F= '$1=="ExecStart"{NF++; $NF="--dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet rs0"}1' file 
Inian
  • 80,270
  • 14
  • 142
  • 161