When you attempt to modify a file without write permission on it, you will end-up with a permission denied error.

1
2
3
4
$ touch donottouch.txt && sudo chown root donottouch.txt
$ cat donottouch.txt
$ echo "change stuff" > donottouch.txt
-bash: donottouch.txt: Permission denied

Using sudo before echo won’t help since the redirection will still apply within your shell environment. Here is few approaches to this problem.

You can obviously switch to a privileged user with sudo -i (see man sudo):

1
2
3
$ sudo -i
Password:
:~ root# echo "change stuff" > donottouch.txt

If you are coding a new shell script for whatever automation project, you may not want require the full script to run as root. An option would be to use sudo and eval the code properly in one-liner:

1
2
3
$ sudo sh -c 'echo "change stuff" > donottouch.txt'
$ cat donottouch.txt
change stuff

A better approach, allowing finer grained permission in sudoers file, would be to use a combination of sudo and tee (aka pipe fitting).

The tee utility copies standard input to standard output, making a copy in zero or more files. The output is unbuffered.

Example Using Tee
1
2
3
4
5
6
7
$ echo "change stuff" | tee donottouch.txt
-bash: donottouch.txt: Permission denied
$ echo "change stuff" | sudo tee donottouch.txt
Password:
change stuff
$ cat donottouch.txt
change stuff

If you don’t want to see the text being display by tee, you just need to redirect stdout to /dev/null.

1
2
3
4
$ echo "change stuff" | sudo tee donottouch.txt >/dev/null
Password:
$ cat donottouch.txt
change stuff

Using tee -a will allow you to append as you would do with >>.

Comments