1、源文件例子
[root@node1 ~]# cat /etc/fstab # # /etc/fstab # Created by anaconda on Mon Mar 1 18:32:15 2021 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # /dev/mapper/centos-root / xfs defaults 0 0 UUID=3fa2b010-61bc-480e-bd49-cb7bee120fe3 /boot xfs defaults 0 0 /dev/mapper/centos-swap swap swap defaults 0 0 [root@node1 ~]#
2、cp一个文件出来 测试修改 fs.txt
sed -i '/swap/s/^/#/g' fs.txt
3、diff看一下 ok了
[root@node1 ~]# diff fs.txt /etc/fstab 11c11 < #/dev/mapper/centos-swap swap swap defaults 0 0 --- > /dev/mapper/centos-swap swap swap defaults 0 0 [root@node1 ~]# cat /etc/fstab
4、如果要幂等执行 得判断是否被注释过了 如果注释过了 则不执行 不然就执行 然后再判断 这个适合用 until 命令
until grep swap fs.txt |grep "#" >/dev/null;do echo "disable swap" && sed -i '/swap/s/^/#/g' fs.txt;done
5、测试OK 换成实际环境 就是下面的 可以重复执行
until grep swap /etc/fstab |grep "#" >/dev/null;do echo "disable swap" && sed -i '/swap/s/^/#/g' /etc/fstab;done