Score:0

How to append a line to /etc/fstab via ssh

cn flag

I have a hdd automount program written.

The software uses ssh in order to issue requests against the target machine. The Idea is that a newly installed hdd is automatically added to fstab.

I have gotten everything working to the point where the fstab line enty is ready to be appended to the file.

I am trying to append like this in my software:

command.RunCommandSudo($"echo \"{mountstring}\" >> /etc/fstab");

resulting in an ssh query of the following format:

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

=> Permission denied

how would be an apropriate way? I doubt the apropriate way for an automated software would be to go through a text editor such as nano?

Matt Murphy avatar
ng flag
I think that command-line indirection (>>) can't be interpreted as being bound to the echo, so to speak. My guess is it ends up taking output from the sudo instead.
Score:2
cn flag

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.

Score:2
id flag

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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.