I want to remove one Line from /etc/fstab
and use the sed
command for that, but it removes everything within my file.
My fstab
:
/dev/mapper/vg00-lv_root / xfs defaults 0 0
/dev/mapper/vg00-lv_backup /backup xfs defaults 0 0
UUID=30d58f5e-a432-4739-98f9-3f2ceb66fc03 /boot ext4 defaults 1 2
/dev/mapper/vg00-lv_wsbackup /wsbackup xfs defaults 0 0
UUID=a59bad9c-8c89-4b20-aadd-e83c4ab22a6c swap swap defaults 0 0
10.10.10.10 /mnt/wsbackup cifs user=user,password=password,domain=domain,vers=2.1 0 0
My script:
MNTDIR="/mnt/wsbackup"
if grep -q "$MNTDIR" "/etc/fstab"
then
sed -i -n "\:$MNTDIR:d" /etc/fstab
else
...
fi
If I use the command sed "\:$MNTDIR:d" /etc/fstab
within my script the output I get looks like I want it to:
[root@labor-ssd ~]# sh check.sh
/dev/mapper/vg00-lv_root / xfs defaults 0 0
/dev/mapper/vg00-lv_backup /backup xfs defaults 0 0
#/dev/sdb /backup ext4 defaults 0 0
UUID=30d58f5e-a432-4739-98f9-3f2ceb66fc03 /boot ext4 defaults 1 2
/dev/mapper/vg00-lv_wsbackup /wsbackup xfs defaults 0 0
UUID=a59bad9c-8c89-4b20-aadd-e83c4ab22a6c swap swap defaults 0 0
INFO: user mount configuration removed
But the changes are not written to the file so I use the -i
option to write the changes to the file. The file is completely empty afterwards and I don't know why.
Best Answer
The
/etc/fstab
file becomes empty because you're not only using-i
but also-n
.The
-n
option turns off the "defaultp
(print) command" which is usually triggered at the end of each cycle.With
-n
, your script truly outputs nothing, not even if you remove the-i
option, because there is nop
command in the script, not even the defaultp
at the end of the cycle, which would have printed all lines that weren't deleted. Since thesed
script outputs nothing, tellingsed
to do the changes in-place with-i
empties the file.So, to resolve your issue, remove
-n
from your command.Personally, I would have written the code as
This allows us to keep a copy of the original
fstab
file.Alternatively,
which would do pretty much the same thing, depending on what
sed
implementation you use.Wrap that in a test on
grep -q -F -e "$mntdir" /etc/fstab
(similarly to what you did already) if you need to avoid doing anything to the file if the$mntdir
string is not found in it, i.e.