I have a small program and I want to ensure that it works on both write protected files and un-write protected files. So, instead of using echo $text > $file or echo $text >> $file, I am instead forced to use echo $text | sudo tee $file and echo $text | sudo tee --append $file, respectively. When I use sudo tee, even if I change the permissions, whenever I use rm on the file, it prompts me like so:$ lssomeFile writeProtectedFile$ rm someFile$ lswriteProtectedFile$ rm writeProtectedFilerm remove write-protected regular file 'writeProtectedFile'? yes$ lsI then poked around on the web, looking for possible solutions to my dilemma. There were only two out there that I could find: incorrect permissions, or a changed set of permissions. I knew the permissions case to be incorrect, because I could easily change the permissions by running sudo chmod xxx filename, which would result in a successful permissions change. I assumed then that there was a problem with the file attributes, so I ran lsattr on the file and it would output -------------e--, same as every other file in the directory.UpdateThe reason I was using tee was to echo text to write protected files, but as a side effect it also write protected regular files... My goal was to, in effect, do something like sudo echo whatever >> /etc/someFile, which does not work, so I found a solution in echo whatever | sudo tee /etc/someFile.
How can I un-write protect file made by tee?
shell script;tee
The command tee, when passed a non-existing file as parameter, will create that file before writing the output to it. By prepending that command with sudo, you are asking your shell to run the tee command as root. The consequence is that the file created by tee is owned by the user starting the command: root, and is therefore read-only for other users. You can see this by yourself if you run ls -l and look at the user and group columns.$ rm -f writeProtectedFile # Removing the file in case it already exists$ echo $text | sudo tee writeProtectedFileyourtext$ ls -ltotal 4-rw-r--r-- 1 root root 9 22.07.2015 14:26 writeProtectedFileThere are several options to overcome this:Create the file as a standard user before asking tee to write to it. tee will then either truncate or simply --append to it, without changing its ownership:$ touch writeProtectedFile # creates the file as standard user$ echo $text | sudo tee writeProtectedFile$ rm writeProtectedFileChange the ownership of the file before trying to delete it:$ echo $text | sudo tee writeProtectedFile$ sudo chown $(whoami) writeProtectedFile # `whoami` returns the current user name$ rm writeProtectedFileTell rm to ignore the fact that the file is write-protected, using -f, --force:$ echo $text | sudo tee writeProtectedFile$ rm --force writeProtectedFile