How to Append a Text/Line to root Owned Files with Sudo Access

Today, I came across a situation where I was writing a script for automation. In the script, I had to append a line to file /etc/fstab which is owned by root. I was using the below line in the script, but it was failing.

$ sudo echo "/dev/vg01/lvol0 /mnt/data xfs defaults 0 0" >> /etc/fstab
-bash: /etc/fstab: Permission denied

Below are the ways to achieve this:

1. Using tee command:

$ echo "/dev/vg01/lvol0      /mnt/data     xfs    defaults        0 0" | sudo tee -a /etc/fstab
/dev/vg01/lvol0      /mnt/data     xfs    defaults        0 0
$ tail -n 1 /etc/fstab
/dev/vg01/lvol0      /mnt/data     xfs    defaults        0 0

Here, tee: read from standard input and write to standard output and files. -a: append to the given FILEs, do not overwrite.

2. Using bash/sh command:

$ sudo bash -c "echo '/dev/vg01/lvol0      /mnt/data     xfs    defaults        0 0' >> /etc/fstab"

-c: If the -c option is present, then commands are read from string.