add proper error handling for all final exec calls
[hband-tools.git] / user-tools / logrotate-counters
blobe130280b1d8e03ba260c6cb6944e7f4050446440
1 #!/bin/bash
3 true <<EOF
4 =pod
6 =head1 NAME
8 logrotate-counters - Increment numbers in file names
10 =cut
12 EOF
15 set -u
16 set -e
17 set -o pipefail
19 . /usr/lib/tool/bash-utils
21 if [ $# = 0 ]
22 then
23 warnx "This command is to increment counters in file names."
24 warnx "Usage: $0 [--dry-run] [basename-1 [basename-2 [...]]]"
25 warnx "Where basename is the file name (eg. \"access.log\") on which numbers in all \"access.log.NUMBER.*\" files are gonna be incremented."
26 exit 1
29 dryrun=''
31 if [ "$1" = --dry-run ]
32 then
33 dryrun=1
34 shift
37 shopt -s extglob
38 shopt -s nullglob
40 LF=$'\n'
41 TAB=$'\t'
43 for basename in "$@"
45 basename_length=${#basename}
46 for filename in "$basename".+([0-9]).*
48 if [ -n "${filename//[!$TAB]/}" -o -n "${filename//[!$LF]/}" ]
49 then
50 warnx "Tab or linefeed char in filename - skipping it: $filename"
51 continue
54 ending=${filename:$basename_length}
55 if [[ $ending =~ ^\.([0-9]+)\.(.+)$ ]]
56 then
57 counter=${BASH_REMATCH[1]}
58 remainder=${BASH_REMATCH[2]}
59 newname=$basename.$[counter+1].$remainder
60 echo "$counter $filename $newname"
62 done |\
63 sort -n -r |\
64 while read -r counter filename newname
66 if [ $dryrun ]
67 then
68 echo "$filename" '->' "$newname"
69 else
70 mv -n -v "$filename" "$newname"
72 done
73 done