Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe command with sudo

I have a script which run this command successfully. I am using this command in another script which gives me error on this line (.md5: Permission denied).

I am running the previous script with sudo.

for i in ${NAME}*
do
    sudo md5sum $i | sed -e "s/$i/${NAME}/" > ${NAME}.md5${i/#${NAME}/}
done
like image 724
Sherry Avatar asked Oct 27 '16 19:10

Sherry


People also ask

What is Sudo in command line?

Sudo stands for SuperUser DO and is used to access restricted files and operations. By default, Linux restricts access to certain parts of the system preventing sensitive files from being compromised.

Can you use Sudo in CMD?

su lets you run a command as another user; sudo (actually an alias to su) lets you run a command elevated. You can also do both, running elevated as a different user.


2 Answers

So you want to redirect output as root. It doesn't matter that you executed the command with sudo, because redirection is not part of the execution, so it's not performed by the executing user of the command, but by your current user.

The common trick is to use tee:

for i in ${NAME}*
do
    md5sum $i | sed -e "s/$i/${NAME}/" | sudo tee ${NAME}.md5${i/#${NAME}/}
done

Note: I dropped the sudo from md5sum, as probably you don't need it.

Note: tee outputs in two directions: the specified file and stdout. If you want to suppress the output on stdout, redirect it to /dev/null.

like image 161
janos Avatar answered Oct 03 '22 07:10

janos


You take the output of sudo md5sum $i and pipe it to a sed which is not running as root. sudo doesn't even know this sed exists.

But that's not the problem, because the sed does not need root permissions. The problem is > ${NAME}.... This redirects the output of sed to the file with this name. But the redirection is actually executed by your shell which is running as your user. And because > is a shell built-in operator, you can not prefix it with sudo.

The simple solution is to use tee. tee is a program (so you can run it with sudo) which writes it's input to the standard output and also to a file (like a T-Pipe, hence the name). So you can just:

for i in ${NAME}*
do
    md5sum $i | sed -e "s/$i/${NAME}/" | sudo tee ${NAME}.md5${i/#${NAME}/}
done

Note this will also dump all hashes to your standard output.

like image 30
das_j Avatar answered Oct 03 '22 06:10

das_j