-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrtail.sh
executable file
·157 lines (130 loc) · 2.39 KB
/
rtail.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/bin/bash
VERSION="0.0.4"
NULL=/dev/null
STDIN=0
STDOUT=1
STDERR=2
VERBOSE=0
host=""
files=""
## is piped ?
if [ -t 0 ]; then
ISATTY=1
else
ISATTY=0
fi
## detect ssh environment arguments
if [[ -z "$SSH_ARGS" ]]; then
SSH_ARGS=""
fi
## detect tail environment arguments
if [[ -z "$TAIL_ARGS" ]]; then
TAIL_ARGS=""
fi
## output program version
version () {
echo $VERSION
}
## outputs program usage
usage () {
echo "usage: rtail [-hvV] [ssh_options] [user@]<host> [tail_options] [files ...]"
}
## outputs verbose information
verbose () {
if [[ "1" == "$VERBOSE" ]]; then
{
printf "verbose: "
echo "$@"
} >&$STDERR
fi
}
## output to stderr
perror () {
{
printf "error: "
echo "$@"
} >&$STDERR
}
## parse program opts and build
## ssh and tail arguments
parse_opts () {
while true; do
arg="$1"
## break on empty arg
if [ "" = "$1" ]; then
break;
fi
## ignore args without a `-' prefix
## but attempt to set host and file(s)
## to tail
if [ "${arg:0:1}" != "-" ]; then
if [[ -z "$host" ]]; then
host="$1"
else
files+="$1 "
fi
shift
continue
fi
## overload these flags and
## pass subsequent arguments
## directly to `tail(1)'
case $arg in
-h|--help)
usage 1
return 1
;;
-V|--version)
version
exit
;;
-v|--verbose)
SSH_ARGS+="-v "
VERBOSE=1
shift
;;
## catch all
*)
if [[ -z "$host" ]]; then
SSH_ARGS+="$1";
elif [[ -z "$files" ]]; then
TAIL_ARGS+="$1"
elif [ "-" = "${arg:0:1}" ]; then
perror "Unknown argument \`${arg}'"
usage
return 1
fi
shift
;;
esac
done
}
rtail () {
## opts
parse_opts "$@" || return 1
## detect missing variables
if [[ -z $host ]]; then
perror "Missing host"
usage
return 1
elif [[ -z $files ]]; then
perror "Missing input file(s)"
usage
return 1
fi
## build command
cmd="ssh $SSH_ARGS $host tail $TAIL_ARGS $files"
## verbose out
verbose "host = $host"
verbose "ssh arguments = '$SSH_ARGS'"
verbose "file(s) = $files"
verbose "tail arguments = '$TAIL_ARGS'"
verbose "command = '$cmd'"
## exec
$cmd
}
if [[ ${BASH_SOURCE[0]} != $0 ]]; then
export -f rtail
else
rtail "$@"
fi