17

I am working on a Ubuntu 12.04 and writing a environment-auto-build shell. In the shell I need to change something in rc.local.

This is my rc.local now.

#!/bin/sh -e
#......

exit 0

I want to modify it like this:

#!/bin/sh -e
#......

nohup sh /bocommjava/socket.sh &

exit 0

Now I use nano to modify it, is there any command that can insert the line into rc.local?

missingcat92
  • 787
  • 2
  • 10
  • 21
  • Have you considered raising this question on askubuntu as well? – Waldir Leoncio Jul 12 '13 at 10:25
  • @wleoncio um... Good advise. but do they allow me to publish my question at two site? – missingcat92 Jul 15 '13 at 09:45
  • I guess so, at least I've never had any problems doing that. ;) – Waldir Leoncio Jul 15 '13 at 10:02
  • @wleoncio I've got a good answer, but finally I decided to use crond(@reboot) to start my socket program. I've learned several ways to do it, so I think there is no need to post another question. Thank you anyway. – missingcat92 Jul 16 '13 at 06:26
  • Good for you! Still, since we're on the subject, if you want to go ahead and post the question there along with the answer (you can do that in stackoverflow too), it's highly encouraged: http://stackoverflow.com/help/self-answer – Waldir Leoncio Jul 16 '13 at 10:19

2 Answers2

34

Use Sed

For Test

sed -e '$i \nohup sh /bocommjava/socket.sh &\n' rc.local

Really Modify

sed -i -e '$i \nohup sh /bocommjava/socket.sh &\n' rc.local
sigmalha
  • 723
  • 6
  • 13
  • yes, this command works. But what does $i mean? I checked many sed article, didn't found the answer. Thank u so much! – missingcat92 Jul 15 '13 at 09:40
  • 7
    $i should be divide into '$' and 'i'. '$' means the last line, 'i' means insert before the current line, so '$i' means insert before the last line. – sigmalha Jul 16 '13 at 04:57
  • 4
    You might want to check `if [ "\`tail -n1 /etc/rc.local\`" != "exit 0" ]; then ...` in case someone has appended a blank line. — It wouldn't be fun to notice some weeks later that the service actually didn't restart, when the machine was rebooted – KajMagnus Jan 13 '15 at 09:44
1

The easiest would be to use a scripted language (ex: python, perl, etc...).

#!/usr/bin/env python
import os

with open('/etc/rc.local') as fin:
    with open('/etc/rc.local.TMP') as fout:
        while line in fin:
            if line == 'exit 0':
                fout.write('nohup sh /bocommjava/socket.sh &\n')
            fout.write(line)

# save original version (just in case)
os.rename('/etc/rc.local', '/etc/rc.local.jic')

os.rename('/etc/rc.loca.TMP', '/etc/rc.local')
user590028
  • 11,364
  • 3
  • 40
  • 57