Rajeev
Rajeev

Reputation: 13

Delete entry from /etc/fstab using sed

I am scripting a solution wherein, when a shared drive is removed from the server, we need to remove the entry from fstab as well.

What I have done till now :

MP="${ServerAddress}:${DirectoryPath} ${MountPoint} nfs defaults 0 0"

while read line; do
                if [ "${MP}" = "${line}" ]; then
                    sed "/${line}/d"
                fi
done < /etc/fstab

this is giving an error >> sed: 1: "/servername.net...": command I expects \ followed by text

Please suggest on this can be deleted.

PS: I am running this as a part of the script, so i dont have to run this individually. While running with the suggested options, I am able to delete.. but during the script, this does not work and gives that error. People commenting on the " or the formatting, its just that I cannot copy from there since that is a remote through terminal server.

Upvotes: 0

Views: 12711

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754790

Note that the shell is case-sensitive and expects " as double quotes and not (a problem now fixed in the question). You need to configure your editor not to capitalize words randomly for you (also now fixed). Note that experimenting on system configuration files is A Bad Idea™. Make a copy of the file and experiment on the copy. Only when you're sure that the script works on the copy do you risk the live file. And then you make a backup of the live file before making the changes. (And avoid doing the experimenting as root if at all possible; that limits the damage you can do.)

Your script as written might as well not use sed. Change the comparison to != and simply use echo "$line" to echo the lines you want to standard output.

MP="${ServerAddress}:${DirectoryPath} ${MountPoint} nfs defaults 0 0"

while read line; do
    if [ "${MP}" != "${line}" ]; then
    echo "$line"
    fi
done < /etc/fstab

Alternatively, you can use sed in a single command. The only trick is that the pattern probably contains slashes, so the \@ notation says 'use @ as the search marker'.

MP="${ServerAddress}:${DirectoryPath} ${MountPoint} nfs defaults 0 0"
sed -e "\@$MP@d" /etc/fstab

If you have GNU sed, when you're satisfied with that, you can add the -i.bak option to overwrite the /etc/fstab file (preserving a copy of the original in /etc/fstab.bak). Or use -i $(date +'%Y%m%d.%H%M%S') to get a backup extension that is the current date/time. Or use version control on the file.

Upvotes: 2

SukkoPera
SukkoPera

Reputation: 621

Try the following:

sed -i.bak "\@^$SERVERADDR:$DIRPATH@d" /etc/fstab

After setting meaningful values for SERVERADDR and DIRPATH. That line will also make a backup of the old file (named fstab.bak). But since /etc/fstab is such an important file, please make sure to have more backups handy.

Let me point out that you only need that single line, no while loop, no script!

Upvotes: 3

Related Questions