Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple bash script to delete anything that might have accumulated in root's home directory, i.e. /root
#!/bin/bash
# ===
# Author: David Tonhofer
# Rights: Public Domain
# ===
set -o nounset
ROOT=/root
if [[ ! -d $ROOT ]]; then
echo "Directory '$ROOT' does not exist, nothing to do!" >&2
exit 0
fi
echo "Will delete file in '$ROOT'"
echo "(except .vimrc, .bash_profile, .bash_logout, .bashrc, .ssh)!"
echo "Proceed? (Type YES for actual deletion, otherwise just press enter for listing)"
read -r
if [[ ${REPLY^^} == YES ]]; then
echo "Actually performing deletion!" >&2
echo >&2
ACTION=Y
else
echo "Not really deleting, just a dry-run!" >&2
echo >&2
ACTION=
fi
# Using "find" here is very unpredictable.
# https://unix.stackexchange.com/questions/164873/find-delete-does-not-delete-non-empty-directories#164882
# Better roll our own loop!
# This actually fills an array with the dotted and nondotted files!
# This works correctly also with files that have names with spaces.
files=("$ROOT"/.* "$ROOT"/*)
for file in "${files[@]}"; do
# loop around if file is gone
# ... or if there is no file and "$file" actually equals the pattern!
[[ -e "$file" ]] || continue
bn=$(basename "$file")
[[ $bn == '.' || $bn == '..' ]] && continue
# jump over some files
case $(basename "$file") in
.vimrc|.bash_profile|.bash_logout|.bashrc|usb|.ssh)
echo "Keeping '$file'" >&2
continue
;;
esac
# Otherwise delete
if [[ -d "$file" ]]; then
if [[ $ACTION == Y ]]; then
echo "Deleting directory '$file'" >&2
/bin/rm -r "$file"
else
echo "Would delete directory '$file'" >&2
fi
elif [[ -f "$file" ]]; then
if [[ $ACTION == Y ]]; then
echo "Deleting file '$file'" >&2
/bin/rm "$file"
else
echo "Would delete file '$file'" >&2
fi
else
echo "Skipping '$file' because it's neither a directory nor a file" >&2
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment