• Uncategorized

About bash : How-would-I-create-a-text-file-and-fill-it-with-sudo-permission-in-bash-duplicate

Question Detail

I’m trying to create and fill a file in a directory that requires sudo permission.

It seems that based on tested the suggested similar post.

sudo su -c "echo 'put in file' > file_name"
echo "Some text" | sudo tee /etc/file

will both create a file within the directory that requires sudo permission

Question Answer

The question has been edited to include a log of the problem being introduced, which includes the command:

# Taken from edited question
$ echo 'hello' > sudo tee /data/hello

In bash (which allows redirection operators at any point in a simple command), this is precisely equivalent to running:

# From question, with redirection moved to end to make actual behavior more readable
echo 'hello' tee /data/hello > sudo

That is, it’s creating a file named sudo in your current directory, not using sudo to run tee (in the above, tee is just an argument to echo).

What you want, by contrast, is:

# CORRECT: Using a pipe, not a redirection
echo 'hello' | sudo tee /data/hello

with a pipe (|) rather than a >.

Assuming you have the required sudo privileges you could use an editor like vi or nano

sudo vi /etc/file


sudo nano /etc/file

If you don’t have sudo for those programs you can su to root first and then try:

sudo su -

vi /etc/file


nano /etc/file

If you want to do it all on one command line, you can make sure that the file exists by running touch(1) on it. E.g.

sudo touch /etc/file && echo "Some text" | sudo tee /etc/file

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.