Bash: Programmatically Add Entries in fstab

Bash: Programmatically Add Entries in fstab

So I have found that it is rather easy to add entries into /etc/fstab while maintaining relatively legible scripts and making the changes with minimal user interaction…

METHOD ONE

This option is the simplest, we simply echo the line into the file as we want it to appear, then based on the >> it is added as the last line in the file.  This is fine, however this does not provide us with a way of inserting tabs, it is simply whitespace.

echo "nfsserver.allanglesit.com:/nfsshare      /mnt/nfs nfs rw,bg,hard,nointr,rsize=131072,wsize=131072,tcp,vers=3" >> /etc/fstab

METHOD TWO

Here we are incorporating the \t special character which is representative of the [tab] key.  With this method we must call echo with the -e parameter which tells it that we plan on adding in special characters and we want echo to translate them instead of treating them as text.  This method has a huge problem…  It is completely unreadable.

echo -e "nfsserver.allanglesit.com:/nfsshare\t/mnt/nfs\tnfs\trw,bg,hard,nointr,rsize=131072,wsize=131072,tcp,vers=3" >> /etc/fstab

METHOD THREE

This is the best of both worlds.  The functionality is there, but we are achieving it with a little more effort, which results in some cleaner code.  And to make it even more legible we can add comments after each line to indicate what each line is doing, as I have done with each tab line.  Another thing to notice, is that we are calling echo with -n to prevent it from creating the standard newline at the end of the entry.  This will allow us to keep pumping data onto the same line.  However we want to not call the -n on the last entry on the line.  Otherwise we will add more data to this same line if we do subsequent redirects into the same file.

echo -n "nfsserver.allanglesit.com:/nfsshare" >> /etc/fstab
echo -e -n "\t" >> /etc/fstab    #INSERT TAB
echo -n "/mnt/nfs" >> /etc/fstab
echo -e -n "\t" >> /etc/fstab    #INSERT TAB
echo -n "nfs" >> /etc/fstab
echo -e -n "\t" >> /etc/fstab    #INSERT TAB
echo "rw,bg,hard,nointr,rsize=131072,wsize=131072,tcp,vers=3" >> /etc/fstab

Of course any of these methods can be adapted in whatever way you need to fit your use case, this isn’t only helpful for /etc/fstab.  That is just what I was using it for.