Skip to content

Instantly share code, notes, and snippets.

@woblerr
Created December 12, 2019 14:01
Show Gist options
  • Save woblerr/193ddbd97fa48294cf6159b800f66bbf to your computer and use it in GitHub Desktop.
Save woblerr/193ddbd97fa48294cf6159b800f66bbf to your computer and use it in GitHub Desktop.
Docker containers logs clearing script

Docker containers logs clearing script

chmod +x ./clear_docker_container_logs.sh

Usage

Usage: ../clear_docker_container_logs.sh [-c "<container>"]

By default, logs for all containers are cleared.

        -c "<container>" Specific container(s) name or docker-compose service(s) name
  • Clear all docker logs
$ sudo ./clear_docker_container_logs.sh
Clear logs for all containers
  • Clear logs for nginx
$ sudo ./clear_docker_container_logs.sh -c "nginx"
Clear logs for "nginx"
  • Clear logs for nginx and app (not exist)
$ sudo ./clear_docker_container_logs.sh -c "nginx app"
Clear logs for "nginx app"
Container or service "app" does not exist.
#!/bin/bash
CLIST=""
help()
{
echo "Usage: $0 [-c \"<container>\"]"
echo ""
echo "By default, logs for all containers are cleared."
echo ""
echo -e "\t-c \"<container>\" Specific container(s) name or docker-compose service(s) name"
exit 1
}
if [ $# == 0 ]; then
echo "Clear logs for all containers"
CLIST="$(docker ps -aq)"
elif [ "$1" == "--" ] || [[ "$1" =~ ^-$ ]] || ! [[ "$1" =~ ^- ]]; then
help
else
while getopts "c:" opt; do
case $opt in
c)
CNAMES+=("$OPTARG")
echo "Clear logs for \"$CNAMES\"" ;;
\?) help ;;
esac
done
shift $((OPTIND -1))
if ! [ "$1" == "" ]; then
help
fi
fi
for i in $CNAMES; do
CONTAINERS=$(docker ps -aq -f name=$i 2> /dev/null)
if [ "$CONTAINERS" == "" ]; then
CONTAINERS="$(docker-compose ps -aq $i 2> /dev/null)"
if [ -z $CONTAINERS ]; then
echo "Container or service \"$i\" does not exist."
fi
fi
CLIST+=$CONTAINERS$'\n'
done
for i in $CLIST; do
log=$(docker inspect -f '{{.LogPath}}' $i 2> /dev/null)
truncate -s 0 $log
done
@oleksandr-luxmedien
Copy link

I was able to release almost 100 Gb using this script. Thanks a lot!

@llccing
Copy link

llccing commented Sep 15, 2023

Thank you very much. This help me a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment