How to add a line to an empty file using sed, but not echo?

I have the following problem: in a script that should not run as root, I need to write a line to a newly created empty file. This file is located in / etc, so I need to elevate privileges in order to write to it.

Creating a file is simple:

sudo touch /etc/myfile

Now just using the echo to write to the file, as if it doesn't work ...

sudo echo "something" > /etc/myfile

... because only the first part of the command (echo) is executed with sudo, but not redirecting to the file.

I used to use something like this ...

sudo sed -i -e "\$aInsert this" /etc/differntfile

... add to the end of the file that worked because the file was not empty. But since sed works on a line-by-line basis, it does nothing, the file remains completely empty.

? ? sed? , ?

+4
1

tee:

echo "something" | sudo tee /etc/myfile   # tee -a to append

/dev/null, :

echo "something" | sudo tee /etc/myfile > /dev/null

- sh -c sudo:

sudo sh -c 'echo "something" > /etc/myfile'

sed: , . sed , , .

+5

Source: https://habr.com/ru/post/1649781/


All Articles