In an earlier post when I was installing and configuring BLAST, I was unable to append a file from the command line using:
$sudo echo 'text I want appended to file' >> filename.sh
I would always get a permission denied error, despite being able to open (and edit) that same file by using the graphical text editor program, “gedit”.
Turns out, that the problem is related to how the “sudo” command is applied to the commands following it. The issue is that “sudo” only gets applied to “echo” and does not get applied to the “redirect” command (the ‘>>’). Thus, “echo” has sudo permissions, but the redirect does not, and cannot append the text to the file.
So, how does one get around this? Apparently, there are two relatively easy ways.
1. Use “sudo” to run a “subshell”. Example:
$sudo sh -c "echo 'text I want to append to a file' >> /path/to/file/filename.sh"
The “sudo” command gets applied to a a new subshell (that’s what the ‘sh’ means; a new shell). Thus, everything that runs in that subshell is governed by the “sudo” permissions.
2. Use “sudo” to execute “tee”. Example:
$echo 'text I want to append to a file' | sudo tee -a /path/to/file/filename.sh
The “sudo” command gets applied to the “tee” function. As such, anything that “tee” executes already has sudo permissions. In the above example, the “echo” command normally sends the text in the single quotes to the screen, but in this instance the text gets “piped” (the ‘|’ symbol) to the subsequent command. The subsequent command is running “tee” with sudo permissions and tells “tee” to append (the ‘-a’ argument) the piped text to our file. Additionally, “tee” will also print the text to the screen, as that’s it’s primary function.