How to append a line to /etc/fstab via ssh [duplicate]
How to append a line to /etc/fstab via ssh [duplicate]
https://askubuntu.com/questions/1367336/how-to-append-a-line-to-etc-fstab-via-ssh
Asked 4 years, 2 months ago Modified 4 years, 2 months ago Viewed 8k times 3
This question already has answers here: How to solve “permission denied” when using sudo with redirection in Bash? (7 answers) Ubuntu 14 - unable to use sudo echo to overwrite files [duplicate] (1 answer) Closed 4 years ago. 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?
command-linepermissionsmountsshfstab Share Improve this question Follow asked Oct 4, 2021 at 12:41 julian bechtold’s user avatar julian bechtold 81511 gold badge88 silver badges1717 bronze badges 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 CommentedOct 4, 2021 at 12:52 the indirection doesn’t inherit sudo permissions so use tee -a as below – krystan honour CommentedApr 1, 2024 at 21:35 Add a comment 2 Answers Sorted by:
Highest score (default) 8
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 Share Improve this answer Follow answered Oct 4, 2021 at 13:18 Terrance’s user avatar Terrance 44k88 gold badges136136 silver badges193193 bronze badges Add a comment 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.