Skip to content

Instantly share code, notes, and snippets.

@ejlevin1
Created October 17, 2020 17:02
Show Gist options
  • Save ejlevin1/2f771ea9e424b0802bde01a407a793e7 to your computer and use it in GitHub Desktop.
Save ejlevin1/2f771ea9e424b0802bde01a407a793e7 to your computer and use it in GitHub Desktop.
Script to follow or purge a docker container log by id or name.
#!/bin/bash
set -e
set -u
set -o pipefail
debug=0
purge=0
follow=0
while getopts 'c:fpn:v' OPTION; do
case "$OPTION" in
c)
container_id="$OPTARG"
;;
f)
follow=1
;;
p)
purge=1
;;
n)
echo "The container name provided is $OPTARG"
container_id=$(docker ps -aqf "name=^$OPTARG$")
;;
v)
verbose=1
;;
?)
echo "script usage: $(basename $0) [-c container_id] [-n container_name] [-v] [-p] [-f]" >&2
echo "-v (verbose)" >&2
echo "-c container_id" >&2
echo "-n container_name" >&2
echo "-p (purge)" >&2
echo "-f (follow)" >&2
exit 1
;;
esac
done
shift "$(($OPTIND -1))"
if [[ -z $container_id ]]; then
echo "No container specified"
exit 1
fi
echo "The container id provided is [$container_id]"
if [[ "$(docker ps -aq -f id=$container_id 2> /dev/null)" == "" ]]; then
echo "Container \"$container_id\" does not exist, exiting."
exit 1
fi
log=$(docker inspect -f '{{.LogPath}}' $container_id 2> /dev/null)
if [[ $log == "" ]]
then
echo "No log file found. Exiting."
exit 0
fi
if [[ $purge -gt 0 ]]
then
echo "Purging log file."
truncate -s 0 $log
fi
if [[ $follow -gt 0 ]]
then
docker logs -f "$container_id"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment