Sherry
Sherry

Reputation: 331

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

Upvotes: 11

Views: 13662

Answers (2)

janos
janos

Reputation: 124724

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
    sudo md5sum "$i" | sed -e "s/$i/${NAME}/" | sudo tee "${NAME}.md5${i/#${NAME}/}"
done

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.

Upvotes: 13

das_j
das_j

Reputation: 4794

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.

Upvotes: 4

Related Questions