Last active
February 3, 2020 17:25
-
-
Save dtonhofer/545db532454bd3f96416e11f35dbeb7b to your computer and use it in GitHub Desktop.
A simple bash script to delete anything that might have accumulated in root's home directory, i.e. /root
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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