2

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?

  • 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. – Matt Murphy Oct 04 '21 at 12:52

2 Answers2

6

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
Terrance
  • 41,612
  • 7
  • 124
  • 183
3

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.

Rinzwind
  • 299,756