0

I've built a docker container and I need to make changes to the service.nginx file.

I have the following variables defined:

LINE=$(cat /usr/lib/systemd/system/nginx.service | grep -n "ExecStart=" | cut -d: -f1)
APPEND=$(cat /usr/lib/systemd/system/nginx.service | grep "ExecStart=")
CONFIG=" -e\ /nginx/nginx.conf"
FILE="/usr/lib/systemd/system/nginx.service"

Output of these are:

13
ExecStart=/usr/sbin/nginx
-e\ /nginx/nginx.conf
/usr/lib/systemd/system/nginx.service

I want to change line 13 in the service file from

ExecStart=/usr/sbin/nginx

to

ExecStart=/usr/sbin/nginx -e\ /nginx/nginx.conf

I tried several awk commands with NR and gsub and for the life of me I can not generate the file.

I was thinking something along the lines of the following:

awk 'NR==$LINE{gsub("$APPEND", "$APPEND$CONFIG)};1' $FILE > tmp && mv tmp $FILE

It's just generating a new file without the changes.

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
  • Could you more generally say that you want to change the definition of the ExecStart line of the nginx service? I'm afraid fixating on line 13 may lead you astray. – Jeff Schaller Dec 13 '19 at 17:38
  • I'll also note here that you may not want to change the /usr/lib version of the file, preferring an /etc/systemd/ version of it... – Jeff Schaller Dec 13 '19 at 17:39
  • [Put down the `awk` and step away from the package-supplied service unit file](http://jdebp.uk./FGA/put-down-the-chocolate-covered-banana.html). Your _actual_ task is that you want to override a setting for a service unit. Like the people at https://unix.stackexchange.com/q/398540/5132 and https://unix.stackexchange.com/q/298581/5132 and https://unix.stackexchange.com/q/66029/5132 did. – JdeBP Dec 13 '19 at 17:53
  • Thanks I just move the entire file into /etc/systemd/system , wasn't aware that this was frowned upon, lesson learned. – Chupacabra Dec 13 '19 at 22:19

1 Answers1

1

The systemd files located in /usr/lib/systemd are not meant to be modified by the user. Unit files can be placed in the /etc/systemd/system to override configurations in the OS supplied unit file. In your case, you need a file named /etc/systemd/system/nginx.service containing only the following:

[Service]
ExecStart=/usr/sbin/nginx -e /nginx/nginx.conf

The reason that your awk example doesn't work is because you are trying to use shell variables inside of single quotes, where they do not expand and remain literal. You can use the -v option for awk to pass in shell variables:

awk -v "LINE=$LINE" -v "APPEND=$APPEND" -v "CONFIG=$CONFIG" 'NR==LINE{gsub(APPEND, APPEND""CONFIG)};1' $FILE > tmp && mv tmp $FILE
jordanm
  • 41,988
  • 9
  • 116
  • 113
  • Thank you for letting me know about the service file location. Also cheers for the solution, I have to pass the variables into awk. Lesson learned. – Chupacabra Dec 13 '19 at 20:09