How to add a line into rc.local with shell

16,284

Solution 1

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

Solution 2

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')
Share:
16,284

Related videos on Youtube

missingcat92
Author by

missingcat92

Updated on September 15, 2022

Comments

  • missingcat92
    missingcat92 over 1 year

    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
    missingcat92 almost 11 years
    Well, this works fine, but I still want a shell solution. Thanks a lot!
  • user590028
    user590028 almost 11 years
    Quite a bit more code in basic shell. Check out bash.cyberciti.biz/file-management/read-a-file-line-by-line
  • missingcat92
    missingcat92 almost 11 years
    yes, this command works. But what does $i mean? I checked many sed article, didn't found the answer. Thank u so much!
  • sigmalha
    sigmalha almost 11 years
    $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.
  • KajMagnus
    KajMagnus over 9 years
    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