Sherry Sherry - 1 month ago 13
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}*
do
sudo md5sum $i | sed -e "s/$i/${NAME}/" > ${NAME}.md5${i/#${NAME}/}
done

Answer

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.