我正在 Ubuntu 12.04 上工作并编写一个环境自动构建 shell。在 shell 中,我需要更改 rc.local 中的某些内容。
这是我现在的 rc.local。
#!/bin/sh -e
#......
exit 0
我想这样修改:
#!/bin/sh -e
#......
nohup sh /bocommjava/socket.sh &
exit 0
现在我用nano来修改它,有没有什么命令可以将行插入到rc.local中?
使用Sed
用于测试
sed -e '$i \nohup sh /bocommjava/socket.sh &\n' rc.local
真正修改
sed -i -e '$i \nohup sh /bocommjava/socket.sh &\n' rc.local
最简单的方法是使用脚本语言(例如:python、perl 等...)。
#!/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')
找到exit 0并将其删除。
在末尾附加 exit 0 的新行。
file="rc.local"
search="exit 0"
newLine="nohup sh /bocommjava/socket.sh &"
# Remove "exit 0"
ex -s +"g/$search/d" -cwq $file
# Append line with "exit 0" in the end
echo "$newLine\n\n$search" >> $file