missingcat92
missingcat92

Reputation: 1086

How to add a line into rc.local with shell

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?

Upvotes: 18

Views: 17612

Answers (3)

Kuza Grave
Kuza Grave

Reputation: 1574

Find exit 0 and remove it.
Append new line with exit 0 in the end.

file=/etc/rc.local
search="exit 0"
newLine="nohup sh /bocommjava/socket.sh &"

# Remove exit 0
sudo ex -s +"g/$search/d" -cwq $file

# Find line
found=$(cat $file | grep "$newLine")

# Remove if exist
if [ "$found" != "" ]; then
    sudo ex -s +"g/$found/d" -cwq $file
fi

# Append lines
sudo echo $found >> $file
sudo echo $search >> $file

Upvotes: 0

sigmalha
sigmalha

Reputation: 733

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

Upvotes: 35

user590028
user590028

Reputation: 11730

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')

Upvotes: 1

Related Questions