Created
July 30, 2013 05:55
-
-
Save liling/6110557 to your computer and use it in GitHub Desktop.
A bash script maintains rotate zfs snapshots
This file contains hidden or 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 | |
| function add_slash { | |
| echo $1 | sed -e 's/\//\\\//' | |
| } | |
| function list_snapshot { | |
| local v=$(add_slash $VOL) | |
| zfs list -t snapshot | awk "/$v@$SNAPSHOT-/"'{print $1}' | |
| } | |
| function count_snapshot { | |
| list_snapshot | wc -l | |
| } | |
| function make_snapshot { | |
| local n=$VOL@$SNAPSHOT-`date +%Y%m%d%H%M%S` | |
| if [[ 1 -eq "$VERBOSE" ]] ; then | |
| echo "Create snapshot $n" | |
| fi | |
| zfs snapshot $n | |
| } | |
| function remove_snapshot { | |
| local c=$(count_snapshot) | |
| local h=`expr $c '-' $KEEP` | |
| if [[ 1 -eq "$VERBOSE" ]] ; then | |
| echo "$h snapshot(s) to be deleted" | |
| fi | |
| if [[ $h -ge 0 ]] | |
| then | |
| local line | |
| local i=0 | |
| for line in $(list_snapshot) | |
| do | |
| i=`expr $i + 1` | |
| if [[ $h -ge $i ]] | |
| then | |
| if [[ 1 -eq "$VERBOSE" ]] ; then | |
| echo "Delete snapshot $line" | |
| fi | |
| zfs destroy $line | |
| fi | |
| done | |
| fi | |
| } | |
| usage() | |
| { | |
| cat << EOF | |
| usage: $0 options zfsvol | |
| This script run the test1 or test2 over a machine. | |
| OPTIONS: | |
| -h Show this message | |
| -s Snapshot prefix, required. | |
| -k Number of snapshots to be kept, required without -l | |
| -l List snapshots | |
| -v Verbose | |
| EOF | |
| } | |
| SNAPSHOT= | |
| KEEP= | |
| while getopts “hs:k:lv” OPTION | |
| do | |
| case $OPTION in | |
| h) | |
| usage | |
| exit 1 | |
| ;; | |
| s) | |
| SNAPSHOT=$OPTARG | |
| ;; | |
| l) | |
| LIST=1 | |
| ;; | |
| k) | |
| KEEP=$OPTARG | |
| ;; | |
| v) | |
| VERBOSE=1 | |
| ;; | |
| ?) | |
| usage | |
| exit | |
| ;; | |
| esac | |
| done | |
| shift $((OPTIND-1)) | |
| VOL=$1 | |
| if [[ 1 -eq "$LIST" ]] | |
| then | |
| list_snapshot | |
| exit 0 | |
| fi | |
| if [[ -z $VOL ]] || [[ -z $SNAPSHOT ]] || [[ -z $KEEP ]] | |
| then | |
| usage | |
| exit 1 | |
| fi | |
| make_snapshot | |
| remove_snapshot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment