编辑没有临时文件的配置文件

时间:2013-08-26 17:22:25

标签: linux bash shell

我正在尝试编写一个简单的脚本来在文件的顶部添加一些配置,这就是我这样做的方法:

 #! /bin/bash

 sudo apt-get install monit
 # BELOW IS THE CODE THAT I'M INTERESTING TO CHANGE 
 echo '
 set eventqueue basedir /etc/monit/eventqueue/ slots 1000
 set mmonit http://monit:monit@xxx.xxx.xxx.xxx:8080/collector
 set httpd port 2812 and use address ec2-xxx.xxx.xx.xx.com 
     allow localhost
     allow 0.0.0.0/0.0.0.0
     allow admin:swordfish
 ' | sudo tee -a /etc/monit/monitrc_tmp
sudo cat /etc/monit/monitrc >> /etc/monit/monitrc_tmp
sudo rm /etc/monit/monitrc
sudo mv /etc/monit/monitrc_tmp /etc/monit/monitrc
# UP TO THIS POINT
sudo sed -i 's/set daemon 120/set daemon 20/' /etc/monit/monitrc
exit 0

正如您所看到的,我正在尝试在文件顶部添加一些配置。并且只想知道是否有任何flagcommand可以帮助我在不创建tmp文件的情况下执行此操作。

2 个答案:

答案 0 :(得分:3)

因为你在Linux上,所以看起来像sed -i的情况。此外,由于这是系统管理工作,请保留备份。

sudo sed -i.bak -e '1i\
set eventqueue basedir /etc/monit/eventqueue/ slots 1000\
set mmonit http://monit:monit@xxx.xxx.xxx.xxx:8080/collector\
set httpd port 2812 and use address ec2-xxx.xxx.xx.xx.com\
    allow localhost\
    allow 0.0.0.0/0.0.0.0\
    allow admin:swordfish
' /etc/monit/monitrc

这表示'在第1行之前插入以下行'...并且行继续向上并包括最后没有反斜杠的行。

你也可以编辑set daemon行,即使你说它超出了范围:

sudo sed -i.bak -e '1i\
set eventqueue basedir /etc/monit/eventqueue/ slots 1000\
set mmonit http://monit:monit@xxx.xxx.xxx.xxx:8080/collector\
set httpd port 2812 and use address ec2-xxx.xxx.xx.xx.com\
    allow localhost\
    allow 0.0.0.0/0.0.0.0\
    allow admin:swordfish
s/set daemon 120/set daemon 20/
' /etc/monit/monitrc

答案 1 :(得分:2)

这应该将行添加到文件的顶部。

  echo -e " set eventqueue basedir /etc/monit/eventqueue/ slots 1000 \n
  set mmonit http://monit:monit@xxx.xxx.xxx.xxx:8080/collector \n
  set httpd port 2812 and use address ec2-xxx.xxx.xx.xx.com \n
      allow localhost \n
      allow 0.0.0.0/0.0.0.0 \n
      allow admin:swordfish \n 
  $(cat /etc/monit/monitrc)" > /etc/monit/monitrc

 sudo sed -i 's/set daemon 120/set daemon 20/' /etc/monit/monitrc
 exit 0