I am creating a small bash script to automate some simple tasks to handle my docker container. One of the commands I have is to clear the logs, but this doesnt work responding with "Permission denied".
The issue with this is I am using sudo
.
if [ $CLEAR_OPT == true ]
then
DOCKER_LOG_PATH=$(docker inspect $DOCKER_ID --format='{{.LogPath}}')
sudo :> $DOCKER_LOG_PATH;
exit 0
fi
This errors out.
However this following sequence of linux commands will not error out:
sudo -s
:> /var/lib/docker/containers/path/path-json.log
I tested without using sudo -s
and it still didnt work in linux terminal.
Is there something I am missing? I thought when doing sudo
it would run the command as root user?
CodePudding user response:
The second line of your "working" example is executed in a new shell that already runs with root privileges, since sudo -s
starts a new shell.
But the :>
in your shell script will be executed by the shell and not by sudo
, so it will run with the original (presumably lower) privileges.
The workaround is to pipe the output of something like echo
to a command using sudo: echo | sudo tee $DOCKER_LOG_PATH
.
An even simpler and more explicit solution is to use a command that's explicitly built to truncate files: sudo truncate -s0 $DOCKER_LOG_PATH
.