Sherry Sherry - 2 months ago 21
Linux Question

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


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

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.