-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhile-read
More file actions
executable file
·303 lines (267 loc) · 9.18 KB
/
while-read
File metadata and controls
executable file
·303 lines (267 loc) · 9.18 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env bash
# -*- mode: sh; sh-shell: bash; indent-tabs-mode: nil; tab-width: 2 -*-
# vim: ft=bash:et:ts=2:sts=2:sw=2
# code: language=bash insertSpaces=true tabSize=2
# shellcheck shell=bash
#
# Monitor input or X clipboard data and execute a command.
declare -r _SCRIPT_PATH="$(cd "$(dirname "$0")"; pwd -P)"
declare -r _SCRIPT_FILE="$(basename "$0")"
# include commons lib
for f in {$_SCRIPT_PATH/,$_SCRIPT_PATH/lib,$HOME/lib}/commons.sh; do
if [[ -f "$f" ]]; then
source "$f"
break
fi
done
if ! command -v "cl::cmd_p" >& /dev/null; then
printf "commons lib not found, exiting ..\n" >&2
exit 1
fi
# set options
set -o errtrace
#set -o errexit
set -o pipefail
set -o nounset
(( ${DEBUG_LVL:-0} >= 2 )) && set -o xtrace
IFS=$'\t\n\0'
# traps
#trap '_rc=$?; \
# printf "ERROR(%s) in %s:%s\n -> %s\n -> %s\n" "${_rc}" \
# "${0:-N/A}" "${LINENO:-N/A}" "${FUNCNAME[@]:-N/A}" \
# c"${BASH_COMMAND:-N/A}"; \
# exit $_rc' ERR
trap 'printf "\nINTERRUPT\n"; exit 1' SIGINT SIGTERM
#trap '_rc=$?; printf "EXIT(%s)\n" "$_rc"; exit $_rc' EXIT
# constants
declare -r _USAGE="${_SCRIPT_FILE} [OPTION..] COMMAND.."
declare _HELP
! IFS='' read -r -d '' _HELP <<EOF
Usage: $_USAGE
Reads text input from command line or X clipboard [--xclip], passing the text
as argument to the given COMMAND..
$(cl::fx b)General:$(cl::fx r)
-b, --background Execute command as job, else: execute in sequence.
-d, --delimiter input delimiter (default: newline \$'\\n')
$(cl::fx b)XClip:$(cl::fx r)
-x, --xclip monitor X clipboard instead of reading terminal input
or windows clipboard in WSL
--pollrate X XClip mode poll-rate in seconds (default: 0.2s)
$(cl::fx b)Filter Input:$(cl::fx r)
-m, --match RE input must match the given regex, else: ignore input
--match-seperate match individual item (separated by --delimiter)
(default: match complete input)
--allow-duplicates Allow repeated input (default: ignore). Affects sequen-
cial repetitions only, depulicates are never tracked
globally. Has no effect on --xclip mode (see below).
$(cl::fx b)Verbosity:$(cl::fx r)
-v, --verbose verbose output, print full command before execution.
-xn, --xnotify use notify-send (if existing) to show each processed
item as a desktop notification
$(cl::fx b)Terminal Input Mode (default):$(cl::fx r)
Reads terminal text input line-by-line. Each time a newline \\n is entered,
COMMAND.. is executed using the given text as final argument.
If a different delimiter is used, the line may be split up into individual
items (e.g. separated by space), each item will executing the COMMAND..
Each {} within the COMMAND.. will be substituted with the given line/item.
If no {} exists the line/item will be appended to the COMMAND... (final arg.)
$(cl::fx b)XClip Mode [-x]:$(cl::fx r)
Reads the X clipboard content in regular intervals (default: 0.2 sec
intervals, see --pollrate). Each X clipboard content change, within the given
interval, is read as input.
Since the clipboard can contine multi-line text, using the default
--delimiter \\n will result in multiple COMMAND.. executions per input (one
per line in clipboard text). The delimiter can be changed but be aware that
multi-line COMMAND.. arguments may be problematic.
Note that the --allow-duplicates option is ignored in XClip mode, since only
clipboard changes are registered as new input.
$(cl::fx b)Background [-b] option and limitations:$(cl::fx r)
Per default commands are executed in sequence (single threaded) meaning that
the input is not monitored while a command is still being executed. In case
of terminal input mode this might work to some degree (until the input buffer
is exausted) but it can result in data loss (input not read).
As a result it is usually sensible to use the [-b], especially in XClip mode
in combination with "long runnning" commands (longer than clipbard change
intervals).
Note that in the current implementation no execution queue exists, meaning
that a combination of long running comamnds and high input frequency can
again result in issues (high load / too many jobs).
$(cl::fx b)Examples:$(cl::fx r)
# read URLs from input, append matches to file 'links' and download
${_SCRIPT_FILE} -b -m '^https?://' echo '{}' \>\> links \; wget -nv -c '{}'
# same but using tee
${_SCRIPT_FILE} -b -m '^https?://' tee -a links "<<<'{}'" \| wget -nv -c -i -
# monitor xclip for URLs and open matches in new firefox tabs
${_SCRIPT_FILE} -x -b -m '^\w+://' firefox --new-tab
EOF
declare -r _HELP
# arguments
declare bg=false
declare xclip=false
declare verbose=false
declare allow_dupes=false
declare match_separate=false
declare xnotify=false
declare delimiter=$'\n'
declare regex=""
declare pollrate=.2
declare cmd_arg
# Are we in a Windows Subsystem Linux?
IS_WSL=false
if [[ $(uname -r) = *Microsoft* ]]; then
IS_WSL=true
fi
# parse arguments
_parse_args() {
if [[ -z "${1:-}" ]]; then
cl::p_usg "$_USAGE"
exit 1
fi
#delim='' # -d DELIM split by delimiter (e.g. \n), execute separately for each entry
while [[ -n "${1:-}" ]]; do
case "$1" in
-x|--xclip)
xclip=true
shift
;;
-m|--match)
if [[ -z "$2" ]]; then
cl::p_err "missing regex value for option [$1]"
exit 1
fi
regex="$2"
shift 2
;;
--match-separate)
match_separate=true
shift
;;
-d|--delimiter)
if [[ -z "$2" ]]; then
cl::p_err "missing delimiter value for option [$1]"
exit 1
fi
delimiter="$2"
shift 2
;;
--allow-duplicates)
allow_dupes=true
shift
;;
-b|--background)
bg=true
shift
;;
-v|--verbose)
verbose=true
shift
;;
-xn|--xnotify)
if cl::cmd_p notify-send; then
xnotify=true
else
cl::p_war "argument $1 ignored, notify-send command not found"
fi
shift
;;
--pollrate)
if [[ -z "$2" ]]; then
cl::p_err "missing decimal value for option [$1]"
exit 1
fi
if [[ ! "$2" =~ ^[0-9]+(s|m|h|d)?$ ]]; then
cl::p_err "invalid value [$2] for option [$1]"
cl::p_err "only numeric values with suffix s (default), m, h, and d are allowed"
exit 1
fi
pollrate="$2"
shift 2
;;
-h|--help)
printf "%s" "$_HELP"
exit 0
;;
-*)
cl::p_err "unknown option [$1]"
exit 1
;;
*)
break
;;
esac
done
if [[ -z "${1:-}" ]]; then
cl::p_err "missing command"
exit 1
fi
cmd_arg="$@"
if ${allow_dupes} && ${xclip}; then
cl::p_war "Ignoring --allow-duplicates option in --xclip mode."
allow_dupes=false
fi
}
# start reading / monitoring
_read_loop() {
local input # current input (xclip content / read line)
local input_prev # input from previous iteration
local item # input or part of input (separated via delimiter)
local first=true # is first iteration?
# keep reeding input
while true; do
# xclip or read lines?
if ${xclip}; then
# poll rate sleep, must come first due to continues below
if ! $first; then
sleep ${pollrate} # poll rate
fi
if ${IS_WSL}; then
input="$(powershell.exe Get-Clipboard)"
else
input="$(xclip -selection clip-board -o -l)"
fi
else
IFS='' read -r -d $'\n' input
fi
first=false
# no input? -> skip
[[ -z "${input}" ]] && continue
# new input identical to previous / clipboard unchanged? -> skip input
[[ ${allow_dupes} && "${input}" = "${input_prev:-}" ]] && continue
# input (no line) match mode and regex doesn't match? -> skip input
[[ ! ${match_separate} && ! "${input}" =~ ${regex} ]] && continue
# process lines/delimiter input, each element at a time (including last)
while IFS='' read -r -d "${delimiter}" item || [ -n "$item" ]; do
[[ ${match_separate} && ! "${item}" =~ ${regex} ]] && continue
local -a cmd
# substitute {}?
if [[ "$@" =~ \{\} ]]; then # contains {}? substitute
# in the command substitute all {} with the given item
# https://stackoverflow.com/a/29613573 escape specials
cmd="$(perl -s -0777 -pe 's/\{\}/\Q$item\E/g' -- -item="${item}" <<<"$@")"
else # no {}? append argument
cmd=("$@")
cmd+=("'${item}'")
fi
# run in background (job)?
if ${bg}; then
# TODO implement a simple queue to limit number of concurrent jobs
${verbose} && cl::p_msg "${cmd[@]} &"
${xnotify} && notify-send -u low 'while-read' "${item}"
bash <<<"${cmd[@]}" &
else
${verbose} && cl::p_msg "${cmd[@]}"
${xnotify} && notify-send -u low 'while-read' "${item}"
#bash <<<"${cmd[@]}"
bash <<<"${cmd[@]}"
fi
done <<<"${input}"
input_prev="${input}"
item=""
done
}
main() {
_parse_args "$@"
_read_loop "${cmd_arg[@]}"
}
main "$@"
exit 0