Skip to content

Instantly share code, notes, and snippets.

@mr-salty
Last active January 21, 2024 21:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr-salty/a66119941e797d9eb49b15ea211ea968 to your computer and use it in GitHub Desktop.
Save mr-salty/a66119941e797d9eb49b15ea211ea968 to your computer and use it in GitHub Desktop.
script to clean up files in the bazel cache
#! /bin/bash -e
#
# clean up everything in CACHE_DIR last accessed more than DAYS days ago.
# also removes files with bogus timestamps in the future.
#
# -----------------------------------------------------------------------
# Copyright 2021 Todd Derr (todd.derr@gmail.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
readonly CACHE_DIR="${1-${HOME}/.cache/bazel}"
readonly DAYS="${2-30}"
readonly dirlist="$(tempfile)"
# something is dropping non-writable directories in the cache
find "${CACHE_DIR}" -type d -a \! -writable -fprint0 ${dirlist}
if [[ -s ${dirlist} ]]; then
echo "Fixing $(tr -cd '\0' < ${dirlist} | wc -c) non-writeable directories"
xargs -0 -a "${dirlist}" chmod +w
fi
echo "Cleaning files in ${CACHE_DIR} with atime >${DAYS} days"
find "${CACHE_DIR}" \( -type f -o -type l \) -a \
\( -atime "+${DAYS}" -o -newermt "1 day" \) -print0 |
xargs -r -0 rm
echo -n "Cleaning empty directories..."
while true; do
# never remove CACHE_DIR itself
find "${CACHE_DIR}" -type d \! -path "${CACHE_DIR}" -empty -fprint0 ${dirlist}
if [[ -s ${dirlist} ]]; then
echo -n '.'
xargs -0 -a "${dirlist}" rmdir
else
break;
fi
done
echo " done."
rm "${dirlist}"
@lalten
Copy link

lalten commented Jun 26, 2023

The shebang should be something like #!/bin/bash. Otherwise you may get an error like ./clean-bazel-cache.sh: 12: [[: not found.

@mr-salty
Copy link
Author

good catch, thanks! fixed.

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