Last active
December 24, 2015 18:29
-
-
Save tyru/6843630 to your computer and use it in GitHub Desktop.
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/sh | |
# vim:ts=4 sw=4 sts=4 et: | |
BACKUP_DIR=/path/to/dir/which/has/yyyymmdd/dirs/under/the/directory | |
ask() { | |
default=$1 | |
msg=$2 | |
echo -n "$msg" >&2 | |
read answer || return 1 | |
[ -n "$default" -a -z "$answer" ] && answer=$default | |
echo -n "$answer" | |
return 0 | |
} | |
die() { | |
echo "$@" | |
exit 1 | |
} | |
cd "$BACKUP_DIR" || die "error: can't chdir to '$BACKUP_DIR'." | |
echo | |
echo "[info] Ctrl-C to exit any prompt..." | |
echo | |
nohup=false | |
if ask y 'nohup? [Y/n]: ' | egrep -q '^[yY]'; then | |
nohup=true | |
fi | |
# Loop until existing & correct date directory is given. | |
# e.g.) | |
# * yyyy/mm/dd | |
# * yyyy/mm | |
# * yyyy | |
while :; do | |
# List yyyy/mm/dd dir. | |
ls -d [0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9] | |
ymd_dir=`ask '' 'which date?: '` | |
# Handle EOF. | |
[ $# -ne 0 ] && exit $# | |
[ -d "$ymd_dir" ] || continue | |
(echo "$ymd_dir" | egrep -q '^[0-9]{4}/[0-9]{2}/[0-9]{2}$') && break | |
(echo "$ymd_dir" | egrep -q '^[0-9]{4}/[0-9]{2}/?$') && break | |
(echo "$ymd_dir" | egrep -q '^[0-9]{4}/?$') && break | |
done | |
emptydir=`mktemp -d` | |
# A faster way to delete millions of files in a directory | |
# http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html | |
delcmd="rsync -a --delete '$emptydir/' '$ymd_dir/'; rmdir '$emptydir'; rmdir -p '$ymd_dir' 2>/dev/null" | |
if $nohup; then | |
# * Change process group ID by perl. | |
# * Run with nohup(1) not to die with login shell. | |
perl -e "setpgrp; exec @ARGV" -- nohup sh -c "$delcmd" >/dev/null 2>&1 & | |
# NOTE: If you want to run 'watch' command in this script, | |
# you need to call setpgrp(2) for above 'nohup' command. | |
# Because SIGINT will be sent to process group | |
# including 'nohup' process. | |
# ('nohup' command doesn't ignore SIGINT, only SIGHUP) | |
#trap 'echo "trapped SIGINT: $?"' 2 | |
watch -n1 'uptime; echo; ps awuxx | egrep -w [r]sync | fgrep -v watch; echo; df -h | |
| egrep "Filesystem|/mnt/"; echo; ls -Cd '"$ymd_dir"'/*' | |
# Not reached here because of Ctrl-C(SIGINT). | |
else | |
sh -c "$delcmd" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment