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
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With