May 2007
Beginner
628 pages
15h 46m
English
You need to keep the most recent N logfiles or backup directories, and purge the remainder, no matter how many there are.
Create an ordered list of the objects, pass them as arguments to a function, shift the arguments by N, and return the remainder:
# cookbook filename: func_shift_by
# Pop a given number of items from the top of a stack,
# such that you can then perform an action on whatever is left.
# Called like: shift_by <# to keep> <ls command, or whatever>
# Returns: the remainder of the stack or list
#
# For example, list some objects, then keep only the top 10.
#
# It is CRITICAL that you pass the items in order with the objects to
# be removed at the top (or front) of the list, since all this function
# does is remove (pop) the number of entries you specify from the top
# of the list.
#
# You should experiment with echo before using rm!
#
# For example:
# rm -rf $(shift_by $MAX_BUILD_DIRS_TO_KEEP $(ls -rd backup.2006*))
#
function shift_by {
# If $1 is zero or greater than $#, the positional parameters are
# not changed. In this case that is a BAD THING!
if (( $1 == 0 || $1 > ( $# - 1 ) )); then
echo ''
else
# Remove the given number of objects (plus 1) from the list.
shift $(( $1 + 1 ))
# Return whatever is left
echo "$*"
fi
}If you try to shift the positional parameters by zero or by more than the total number of positional parameters ($#), shift will do nothing. If you are using shift to process a list then delete ...
Read now
Unlock full access