How to append a line to /etc/fstab via ssh [duplicate]

Solution 1:

Like this

sudo su -c "echo 'UUID=X /mnt/test ext4 defaults 0 1' >> /etc/fstab"

Mind that a script like this should be used by user root and not your admin so that would negate the use of sudo.

I am more into doing it like this:

grep -q '/mnt/test' /etc/fstab || 
printf 'UUID=X /mnt/test ext4 defaults 0 1\n' >> /etc/fstab

using user root to do this.

Solution 2:

Another way is to use the tee command.

NAME
       tee - read from standard input and write to standard output and files

SYNOPSIS
       tee [OPTION]... [FILE]...

DESCRIPTION
       Copy standard input to each FILE, and also to standard output.

       -a, --append
              append to the given FILEs, do not overwrite

So, for your command you could do it this way:

echo "UUID=X /mnt/test ext4 defaults 0 1" | sudo tee -a /etc/fstab