minor improvements
[distro-setup] / brc
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4 # this gets sourced. shebang is just for file mode detection
5
6 # Use source ~/.bashrc instead of doing bash -l when running a script
7 # so this can set extdebug and avoid the bash debugger.
8 if [[ -s /a/bin/errhandle/err ]]; then
9 source /a/bin/errhandle/err
10 elif [[ -s $bashrc_dir/err ]]; then
11 # shellcheck source=/a/bin/errhandle/err
12 source $bashrc_dir/err
13 fi
14
15 # In t8, it runs clear_console for login shells by default. I don't want
16 # my console cleared. And linux ttys get cleared without this.
17 if shopt login_shell >/dev/null && [[ -e ~/.bash_logout ]]; then
18 rm ~/.bash_logout
19 fi
20
21 # if [[ -s /usr/share/bash-completion/completions/git ]]; then
22 # source /usr/share/bash-completion/completions/git
23 # fi
24 # if [[ -s /usr/share/bash-completion/completions/gitk ]]; then
25 # source /usr/share/bash-completion/completions/gitk
26 # fi
27
28 # for testing error catching:
29 # t2() {
30 # echo t2
31 # grep sdf sdfd
32 # echo wtf
33 # }
34 # t1() {
35 # echo t1
36 # t2 a b c
37 # }
38
39 # * settings
40
41 CDPATH=.
42
43
44 # remove all aliases. aliases provided by the system tend to get in the way,
45 # for example, error happens if I try to define a function the same name as an alias
46 unalias -a
47
48 # remove gnome keyring warning messages
49 # there is probably a more proper way, but I didnt find any easily on google
50 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
51 #unset GNOME_KEYRING_CONTROL
52
53 # use extra globing features.
54 shopt -s extglob
55 # include .files when globbing, but ignore files name . and ..
56 # setting this also sets dotglob.
57 export GLOBIGNORE="*/.:*/.."
58
59 # Useful info. see man bash.
60 PS4='$LINENO+ '
61
62
63 # broken with bash_completion package. Saw a bug for this once. dont anymore.
64 # still broken in wheezy
65 # still buggered in latest stable from the web, version 2.1
66 # perhaps its fixed in newer git version, which fails to make for me
67 # this note is from 6-2014.
68 # still broken in flidas.
69 #shopt -s nullglob
70
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
73
74 # fix spelling errors for cd, only in interactive shell
75 shopt -s cdspell
76 # append history instead of overwritting it
77 shopt -s histappend
78 # for compatibility, per gentoo/debian bashrc
79 shopt -s checkwinsize
80 # attempt to save multiline single commands as single history entries.
81 shopt -s cmdhist
82 # enable **
83 shopt -s globstar
84
85
86 # inside emacs fixes
87 if [[ $LC_INSIDE_EMACS ]]; then
88 # EMACS is used by bash on startup, but we dont need it anymore.
89 # plus I hit a bug in a makefile which inherited it
90 unset EMACS
91 export LC_INSIDE_EMACS
92 export PAGER=cat
93 export MANPAGER=cat
94 # scp completion does not work, but this doesnt fix it. todo, figure this out
95 #complete -r scp &> /dev/null
96 # todo, remote file completion fails, figure out how to turn it off
97 export NODE_DISABLE_COLORS=1
98 # This gets rid of ugly terminal escape chars in node repl
99 # sometime, Id like to have completion working in emacs shell for node
100 # the offending chars can be found in lib/readline.js,
101 # things that do like:
102 # stream.write('\x1b[' + (x + 1) + 'G');
103 # We can remove them and keep readline, for example by doing this
104 # to start a repl:
105 #!/usr/bin/env nodejs
106 # var readline = require('readline');
107 # readline.cursorTo = function(a,b,c) {};
108 # readline.clearScreenDown = function(a) {};
109 # const repl = require('repl');
110 # var replServer = repl.start('');
111 #
112 # no prompt, or else readline complete seems to be confused, based
113 # on our column being different? node probably needs to send
114 # different kind of escape sequence that is not ugly. Anyways,
115 # completion doesnt work yet even with the ugly prompt, so whatever
116 #
117 export NODE_NO_READLINE=1
118
119 fi
120
121 export SSH_CONFIG_FILE_OVERRIDE=/root/.ssh/confighome
122
123 # emacs has a different default search path than the info command. This
124 # adds the info defaults to emacs, but not the reverse, because I dun
125 # care much about the cli. The search path is only on the cli if you run
126 # "info xxx", or in emacs if you run '(info xxx)', so not that
127 # important, but might as well fix it.
128
129 # info info says this path is what was compiled, and its not documented
130 # anywhere. Through source grepping, i found it in filesys.h of the info
131 # source in trisquel flidas.
132 #
133 # Traling : means for emacs to add its own stuff on to the end.
134
135 export INFOPATH=$PATH:/usr/local/info:/usr/info:/usr/local/lib/info:/usr/lib/info:/usr/local/gnu/info:/usr/local/gnu/lib/info:/usr/gnu/info:/usr/gnu/lib/info:/opt/gnu/info:/usr/share/info:/usr/share/lib/info:/usr/local/share/info:/usr/local/share/lib/info:/usr/gnu/lib/emacs/info:/usr/local/gnu/lib/emacs/info:/usr/local/lib/emacs/info:/usr/local/emacs/info:.:
136
137 # for openwrt system that has no stty, this is easier than
138 # guarding every time i use it.
139 if ! type -p stty >/dev/null; then
140 stty() { :; }
141 fi
142
143
144 use_color=false
145 if [[ $- == *i* ]]; then
146 # for readline-complete.el
147 if [[ $LC_INSIDE_EMACS ]]; then
148 # all for readline-complete.el
149 stty echo
150 bind 'set horizontal-scroll-mode on'
151 bind 'set print-completions-horizontally on'
152 bind '"\C-i": self-insert'
153 else
154
155
156 if [[ $TERM != dumb ]] && test -t 1; then
157 use_color=true
158 fi
159
160 if [[ $KONSOLE_PROFILE_NAME ]]; then
161 TERM=xterm-256color
162 fi
163
164 if [[ $TERM == alacritty && ! -e /usr/share/terminfo/a/alacritty ]]; then
165 # todo: we should try installing the alacritty terminfo if it is not found
166 # https://github.com/alacritty/alacritty/issues/2838
167 TERM=xterm-256color
168 fi
169
170 # copying from the alacritty example above,
171 if [[ $TERM == xterm-kitty ]]; then
172 if [[ ! -e /usr/share/terminfo/x/xterm-kitty ]]; then
173 TERM=xterm-256color
174 else
175 if [[ -e /a/opt/kitty/shell-integration/bash/kitty.bash ]]; then
176 KITTY_SHELL_INTEGRATION=t
177 source /a/opt/kitty/shell-integration/bash/kitty.bash
178 fi
179 fi
180 fi
181
182 # todo: not sure this works in sakura
183 #stty werase undef
184 #bind "\C-w": kill-region
185 # sakura == xterm-256color
186 # konsole == xterm
187 if [[ $TERM != xterm-kitty && $TERM == xterm* ]]; then
188 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
189 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
190 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
191 else
192 # make ctrl-backspace work. for konsole, i fixed it through
193 # /home/iank/.local/share/konsole/default.keytab
194 stty werase ^h
195 bind '"\eOc": shell-forward-word'
196 bind '"\eOd": shell-backward-word'
197 fi
198 # i cant remember why i did this, probably to free up some keys to bind
199 # to other things in bash.
200 # other than C-c and C-z, the rest defined by stty -a are, at least in
201 # gnome-terminal, overridden by bash, or disabled by the system
202 stty lnext undef stop undef start undef
203 fi
204
205 fi
206
207 case $TERM in
208 # fixup broken backspace in chroots
209 xterm-kitty|alacritty)
210 chroot() {
211 TERM=xterm-256color command chroot "$@"
212 }
213 ;;
214 esac
215
216 export BC_LINE_LENGTH=0
217
218 # ansible option
219 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
220
221 # note, if I use a machine I dont want files readable by all users, set
222 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
223
224 # i for insensitive. the rest from
225 # X means dont remove the current screenworth of output upon exit
226 # R means to show colors n things
227 export LESS=RXij12
228 export SYSTEMD_LESS=$LESS
229
230 export NNN_COLORS=2136
231
232 export SL_FILES_DIR=/b/ds/sl/.iank
233 export SL_INFO_DIR=/p/sshinfo
234
235
236 # * include files
237
238 if [[ -s $bashrc_dir/path-add-function ]]; then
239 source $bashrc_dir/path-add-function
240 if [[ $SSH_CLIENT ]]; then
241 if grep -qF /home/iank/.iank/e/e /etc/exports &>/dev/null; then
242 export EMACSDIR=/home/iank/.iank/e/e
243 fi
244 path-add $bashrc_dir
245 fi
246 fi
247
248 # if someone exported $SOE (stop on error), catch errors.
249 #
250 # Note, on debian this results in the following warning when in ssh,
251 # hich I haven't figured out how to fix. It doesn't happen if we source
252 # after the shell has started
253 #
254 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
255 # bash: warning: cannot start debugger; debugging mode disabled
256 if [[ $SOE ]]; then
257 if [[ -e /a/bin/errhandle/err ]]; then
258 source /a/bin/errhandle/err
259 fi
260 fi
261
262
263 mysrc() {
264 local path dir file
265 path=$1
266 dir=${path%/*}
267 file=${path##*/}
268 if [[ -s $path ]]; then
269 source $path
270 elif [[ -s $bashrc_dir/$file ]]; then
271 source $bashrc_dir/$file
272 fi
273 }
274
275
276 mysrc /a/bin/small-misc-bash/ll-function
277 mysrc /a/bin/distro-functions/src/package-manager-abstractions
278
279
280 # * functions
281 ccomp() { # copy completion
282 local src=$1
283 local c
284 shift
285 if ! c=$(complete -p $src 2>/dev/null); then
286 _completion_loader $src &>/dev/null ||:
287 c=$(complete -p $src 2>/dev/null) || return 0
288 fi
289 # remove $src( .*|$)
290 c=${c% $src}
291 c=${c%% $src *}
292 eval $c $*
293 }
294
295
296 ..() { c ..; }
297 ...() { c ../..; }
298 ....() { c ../../..; }
299 .....() { c ../../../..; }
300 ......() { c ../../../../..; }
301
302 chere() {
303 local f path
304 for f; do
305 path=$(readlink -e "$f")
306 echo "cat >$path <<'EOF'"
307 cat "$f"
308 echo EOF
309 done
310 }
311
312
313 # file cut copy and paste, like the text buffers :)
314 # I havnt tested these.
315 _fbufferinit() { # internal use
316 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
317 rm -rf "${my_f_tempdir:?}"/*
318 }
319 fcp() { # file cp
320 _fbufferinit
321 cp "$@" "$my_f_tempdir"/
322 }
323 fct() { # file cut
324 _fbufferinit
325 mv "$@" "$my_f_tempdir"/
326 }
327 fpst() { # file paste
328 [[ $2 ]] && { echo too many arguments; return 1; }
329 target=${1:-.}
330 cp "$my_f_tempdir"/* "$target"
331 }
332
333 _khfix_common() {
334 local host ip port file key
335 read -r host ip port < <(timeout -s 9 2 ssh -oBatchMode=yes -oControlMaster=no -oControlPath=/ -v $1 |& sed -rn "s/debug1: Connecting to ([^ ]+) \[([^\]*)] port ([0-9]+).*/\1 \2 \3/p" ||: )
336 file=$(readlink -f ~/.ssh/known_hosts)
337 if [[ ! $ip ]]; then
338 echo "khfix: ssh failed"
339 return 1
340 fi
341 if [[ $port != 22 ]]; then
342 ip_entry="[$ip]:$port"
343 host_entry="[$host]:$port"
344 else
345 ip_entry=$ip
346 host_entry=$host
347 fi
348 tmpfile=$(mktemp)
349 if [[ $host != $ip ]]; then
350 key=$(ssh-keygen -F "$host_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
351 if [[ $key ]]; then
352 grep -Fv "$key" "$file" | sponge "$file"
353 fi
354 fi
355 key=$(ssh-keygen -F "$ip_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
356 if [[ $key ]]; then
357 grep -Fv "$key" "$file" | sponge "$file"
358 fi
359 ll ~/.ssh/known_hosts
360 rootsshsync
361 }
362 khfix() { # known hosts fix
363 _khfix_common "$@" || return 1
364 ssh $1 :
365 }
366 khcopy() {
367 _khfix_common "$@"
368 ssh-copy-id $1
369 }
370
371 a() {
372 local x
373 x=$(readlink -nf "${1:-$PWD}")
374 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
375 echo -n "$x" | xclip -selection clipboard
376 echo -n "$x" | xclip
377 }
378
379 # a1 = awk {print $1}
380 for field in {1..20}; do
381 eval a$field"() { awk '{print \$$field}'; }"
382 done
383 # h1 = head -n1
384 for num in {1..9}; do
385 eval h$num"() { head -n$num; }"
386 done
387
388
389 hexipv4() {
390 printf '%d.%d.%d.%d\n' $(echo $1 | sed 's/../0x& /g')
391 }
392
393 vp9() {
394 local f out outdir in
395 outdir=vp9
396 case $1 in
397 --out)
398 outdir=$2
399 shift 2
400 ;;
401 esac
402 m mkdir -p $outdir
403 for f; do
404 out=$PWD/$outdir/$f
405 in=$PWD/$f
406 m cd $(mktemp -d)
407 pwd
408 m ffmpeg -threads 0 -i $in -g 192 -vcodec libvpx-vp9 -vf scale=-1:720 -max_muxing_queue_size 9999 -b:v 750K -pass 1 -an -f null /dev/null
409 m ffmpeg -y -threads 0 -i $in -g 192 -vcodec libvpx-vp9 -vf scale=-1:720 -max_muxing_queue_size 9999 -b:v 750K -pass 2 -c:a libvorbis -qscale:a 5 $out
410 cd -
411 done
412 }
413
414 utcl() { # utc 24 hour time to local hour 24 hour time
415 echo "print( ($1 $(date +%z | sed -r 's/..$//;s/^(-?)0*/\1/')) % 24)"|python3
416 }
417
418 declare -a _iankdirf _iankdirb
419
420
421 # ## old wcd, to be deleted
422 # b() {
423 # # backwards
424 # c -
425 # }
426 # # shellcheck disable=SC2032
427 # f() {
428 # # cd forward
429 # c +
430 # }
431 # cl() {
432 # # choose recent directory. cl = cd list
433 # c =
434 # }
435 # # c. better cd
436 # if ! type -t c &>/dev/null; then
437 # if type -p wcd &>/dev/null; then
438 # if [[ $LC_INSIDE_EMACS ]]; then
439 # c() { wcd -c -z 50 -o "$@"; }
440 # else
441 # # lets see what the fancy terminal does from time to time
442 # c() { wcd -c -z 50 "$@"; }
443 # fi
444 # else
445 # c() { cd "$@"; }
446 # fi
447 # fi
448
449 # c. better cd.
450 # keep 2 stacks, forward and back. the top of the back is $PWD
451 # as long as the last directory change was due to c,b,or cl.
452 c() {
453 # normally, the top of dirb is our current dir. if it isn't,
454 # put it on there, except we don't want to do that when we
455 # just launched a shell
456 if [[ $OLDPWD ]]; then
457 if (( ${#_iankdirb[@]} == 0 )) || [[ ${_iankdirb[-1]} != "$PWD" ]]; then
458 _iankdirb+=("$PWD")
459 fi
460 fi
461 cd "$@"
462 if (( ${#_iankdirb[@]} == 0 )) || [[ ${_iankdirb[-1]} != "$PWD" ]]; then
463 _iankdirb+=("$PWD")
464 fi
465 echo "$PWD" >> ~/.iankdirs
466 }
467 ccomp cd c
468
469 bwm() {
470 s bwm-ng -T avg -d
471 }
472
473 b() {
474 local topb
475 if (( ${#_iankdirb[@]} == 0 )); then
476 echo "nothing left to go back to" >&2
477 return 0
478 fi
479 topb="${_iankdirb[-1]}"
480
481 if [[ $topb == "$PWD" ]] && (( ${#_iankdirb[@]} == 1 )); then
482 echo "already on last back entry" >&2
483 return 0
484 fi
485
486
487 if [[ $topb == "$PWD" ]]; then
488 # add to dirf if not already there
489 if (( ${#_iankdirf[@]} == 0 )) || [[ ${_iankdirf[-1]} != "$topb" ]]; then
490 _iankdirf+=("$topb")
491 fi
492 unset "_iankdirb[-1]"
493 cd "${_iankdirb[-1]}"
494 else
495 if (( ${#_iankdirf[@]} == 0 )) || [[ ${_iankdirf[-1]} != "$PWD" ]]; then
496 _iankdirf+=("$PWD")
497 fi
498 cd "$topb"
499 fi
500
501 # give us a peek at what is next in the list
502 # if (( ${#_iankdirb[@]} >= 2 )); then
503 # printf "%s\n" "${_iankdirb[-2]}"
504 # fi
505 }
506
507 f() {
508 local topf
509 if (( ${#_iankdirf[@]} == 0 )); then
510 echo "no forward dir left" >&2
511 return 0
512 fi
513 topf="${_iankdirf[-1]}"
514 unset "_iankdirf[-1]"
515 c "$topf"
516
517 # give us a peek at what is next in the list
518 # if (( ${#_iankdirf[@]} )); then
519 # printf "%s\n" "${_iankdirf[-1]}"
520 # fi
521 }
522
523 # a b c (d)
524 ## back
525 # a b (c)
526 # d
527 #back
528 #a (b)
529 #d c
530 #back
531 #(a)
532 #d c b
533 #forward
534 #a (b)
535 #d c
536 #
537 # a b c
538 ## back
539 # a b
540 # (c)
541 ## forward
542
543 cl() {
544 local i line input start tmpfile
545 local -A buttondirs alines
546 local -a buttons dirs lines
547 buttons=( {a..z} {2..9} )
548 if [[ ! -s ~/.iankdirs ]]; then
549 echo nothing in ~/.iankdirs
550 return 0
551 fi
552
553 i=0
554
555 # note, alternate approach like this, made the following read fail
556 # done < <(tac ~/.iankdirs | awk '!seen[$0]++')
557 # bash: read: read error: 0: Input/output error
558 # which went away by adding a sleep 1 after it.
559
560 mapfile -t lines <~/.iankdirs
561 start=$(( ${#lines[@]} - 1 ))
562
563 # we have ~33 buttons as of this writing, so lets
564 # prune down the history every once in a while.
565 if (( start > 500 )); then
566 tmpfile=$(mktemp)
567 tac ~/.iankdirs | awk '!seen[$0]++' | head -n 200 >$tmpfile
568 cat $tmpfile > ~/.iankdirs
569 fi
570
571 for (( j=$start; j >= 0; j-- )); do
572 line="${lines[$j]}"
573 if [[ ! $line || ${alines[$line]} || ! -d "$line" || $line == "$PWD" || line == "$HOME" ]]; then
574 continue
575 fi
576 alines[$line]=t
577 buttondirs[${buttons[i]}]="$line"
578 printf "%s %s\n" ${buttons[i]} "$line"
579 if (( i == ${#buttons[@]} - 1 )); then
580 break
581 fi
582 i=$(( i + 1 ))
583 done
584
585 if (( i == 0 )); then
586 echo "no dirs in ~/.iankdirs"
587 return 0
588 fi
589 read -r -N 1 input
590 if [[ $input != $'\n' ]]; then
591 c ${buttondirs[$input]}
592 fi
593 }
594 bl() {
595 local start i j max
596 max=10
597 start=$(( ${#_iankdirb[@]} - 1 ))
598
599 # cleanup possible repeating of pwd
600 if (( start >= 0 )) && [[ ${_iankdirb[$start]} == "$PWD" ]]; then
601 start=$(( start - 1 ))
602 fi
603 j=1
604 if (( start >= 0 )); then
605 for (( i=$start; i >= 0 ; i-- )); do
606 printf "%s %s\n" $j ${_iankdirb[i]}
607 j=$(( j + 1 ))
608 if (( j >= max )); then
609 break
610 fi
611 done
612 fi
613
614 max=10
615
616 start=$(( ${#_iankdirf[@]} - 1 ))
617
618 # cleanup possible repeating of pwd
619 if (( start >= 0 )) && [[ ${_iankdirf[$start]} == "$PWD" ]]; then
620 start=$(( start - 1 ))
621 fi
622 if (( start < 0 )); then
623 return 0
624 fi
625 echo --
626 j=1
627 for (( i=$start; i >= 0 ; i-- )); do
628 printf "%s %s\n" $j ${_iankdirf[i]}
629 j=$(( j + 1 ))
630 if (( j >= max )); then
631 break
632 fi
633 done
634 }
635
636
637
638 c4() { c /var/log/exim4; }
639
640 caa() { git commit --amend --no-edit -a; }
641
642 cf() {
643 for f; do
644 hr
645 echo "$f"
646 hr
647 cat "$f"
648 done
649 }
650 caf() {
651 # shellcheck disable=SC2033
652 find -L "$@" -type f -not \( -name .svn -prune -o -name .git -prune \
653 -o -name .hg -prune -o -name .editor-backups -prune \
654 -o -name .undo-tree-history -prune \) \
655 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
656
657 }
658 ccomp cat cf caf
659
660 calc() { echo "scale=3; $*" | bc -l; }
661 # no having to type quotes, but also no command history:
662 clc() {
663 local x
664 read -r x
665 echo "scale=3; $x" | bc -l
666 }
667
668 cam() {
669 git commit -am "$*"
670 }
671
672 ccat () { # config cat. see a config without extra lines.
673 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
674 }
675 ccomp grep ccat
676
677 chrbind() {
678 local d
679 # dev/pts needed for pacman signature check
680 for d in dev proc sys dev/pts; do
681 [[ -d $d ]]
682 if ! mountpoint $d &>/dev/null; then
683 m s mount -o bind /$d $d
684 fi
685 done
686 }
687 chumount() {
688 local d
689 # dev/pts needed for pacman signature check
690 for d in dev/pts dev proc sys; do
691 [[ -d $d ]]
692 if mountpoint $d &>/dev/null; then
693 m s umount $d
694 fi
695 done
696 }
697
698
699 _cdiff-prep() {
700 # join options which are continued to multiples lines onto one line
701 local first=true
702 while IFS= read -r line; do
703 # remove leading spaces/tabs. assumes extglob
704 if [[ $line == "[ ]*" ]]; then
705 line="${line##+( )}"
706 fi
707 if $first; then
708 pastline="$line"
709 first=false
710 elif [[ $line == *=* ]]; then
711 echo "$pastline" >> "$2"
712 pastline="$line"
713 else
714 pastline="$pastline $line"
715 fi
716 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
717 echo "$pastline" >> "$2"
718 }
719
720 cdiff() {
721 # diff config files,
722 # setup for format of postfix, eg:
723 # option = stuff[,]
724 # [more stuff]
725 local pastline unified f1 f2
726 unified="$(mktemp)"
727 f1="$(mktemp)"
728 f2="$(mktemp)"
729 _cdiff-prep "$1" "$f1"
730 _cdiff-prep "$2" "$f2"
731 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
732 while IFS= read -r line; do
733 # the default bright red / blue doesnt work in emacs shell
734 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
735 done < "$unified"
736 }
737
738
739 cat-new-files() {
740 local start=$SECONDS
741 local dir="$1"
742 # shellcheck disable=SC2030
743 inotifywait -m "$dir" -e create -e moved_to | \
744 while read -r filedir _ file; do
745 cat "$filedir$file"
746 hr
747 calc $((SECONDS - start)) / 60
748 sleep 5
749 done
750
751 }
752
753 # shellcheck disable=SC2032
754 chown() {
755 # makes it so chown -R symlink affects the symlink and its target.
756 if [[ $1 == -R ]]; then
757 shift
758 command chown -h "$@"
759 command chown -R "$@"
760 else
761 command chown "$@"
762 fi
763 }
764
765 cim() {
766 git commit -m "$*"
767 }
768
769
770 d() { builtin bg "$@"; }
771 ccomp bg d
772
773 dc() {
774 diff --strip-trailing-cr -w "$@" # diff content
775 }
776 ccomp diff dc
777
778 despace() {
779 local x y
780 for x in "$@"; do
781 y="${x// /_}"
782 safe_rename "$x" "$y"
783 done
784 }
785
786 # get ipv4 ip from HOST. or if it is already a number, return that
787 hostip() {
788 local host="$1"
789 case $host in
790 [0-9:])
791 echo "$host"
792 ;;
793 *)
794 getent ahostsv4 "$host" | awk '{ print $1 }' | head -n1
795 ;;
796 esac
797 }
798
799 dig() {
800 command dig +nostats +nocmd "$@"
801 }
802 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
803 digsort() {
804 local sec
805 sec=
806 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
807 if [[ $l == [^\;]* ]]; then
808 sec+="$l"$'\n'
809 else
810 if [[ $sec ]]; then
811 printf "%s" "$sec" | sort
812 sec=
813 fi
814 printf "%s\n" "$l"
815 fi
816 done
817 }
818 ccomp dig digsort
819 # compare digs to the 2 servers
820 # usage: digdiff @server1 @server2 DIG_ARGS
821 # note: only the soa master nameserver will respond with
822 # ra "recursive answer" flag. That difference is meaningless afaik.
823 digdiff() {
824 local s1 s2
825 s1=$1
826 shift
827 s2=$1
828 shift
829 digsort $s1 "$@" | tee /tmp/digdiff
830 diff -u /tmp/digdiff <(digsort $s2 "$@")
831 }
832
833 dt() {
834 date "+%A, %B %d, %r" "$@"
835 }
836 dtr() {
837 date -R "$@"
838 }
839 ccomp date dt dtr
840
841 dus() { # du, sorted, default arg of
842 du -sh ${@:-*} | sort -h
843 }
844 ccomp du dus
845
846
847 e() { printf "%s\n" "$*"; }
848
849 # echo args
850 ea() {
851 if (( ! $# )); then
852 echo no args
853 fi
854 for arg; do
855 printf "%qEOL\n" "${arg}"
856 printf "%s" "${arg}" |& hexdump -C
857 done
858 }
859 # echo vars. print var including escapes, etc
860 ev() {
861 if (( ! $# )); then
862 echo no args
863 fi
864 for arg; do
865 if [[ -v $arg ]]; then
866 printf "%qEOL\n" "${!arg}"
867 printf "%s" "${!arg}" |& hexdump -C
868 else
869 echo arg $arg is unset
870 fi
871 done
872 }
873
874 ediff() {
875 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
876 emacs --eval "(ediff-files \"$1\" \"$2\")"
877 }
878
879 # mail related
880 etail() {
881 tail -F /var/log/exim4/mainlog -n 200 "$@"
882 }
883 etail2() {
884 tail -F /var/log/exim4/mymain -n 200 "$@"
885 }
886
887 ccomp tail etail etail2
888
889 # print exim old pids
890 eoldpids() {
891 local configtime pid piduptime now daemonpid
892 printf -v now '%(%s)T' -1
893 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
894 if [[ -s /run/exim4/exim.pid ]]; then
895 daemonpid=$(cat /run/exim4/exim.pid)
896 fi
897 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
898 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
899 if [[ $pid == $daemonpid ]]; then
900 continue
901 fi
902 piduptime=$(awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/$pid/stat) ||: # sometimes pids disappear pretty fast
903 if (( configtime > now - piduptime )); then
904 echo $pid
905 fi
906 done
907 }
908
909 # exim tail but only watch lines from new pids
910 etailnew() {
911 local pid oldpids
912 for pid in $(eoldpids); do
913 oldpids+="$pid|"
914 done
915 if [[ $oldpids ]]; then
916 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
917 else
918 etail
919 fi
920 }
921 # exim watch as old pids go away
922 ewatchold() {
923 local configtime pid piduptime now
924 local -i count
925 local -a oldpids
926 count=0
927 while true; do
928 oldpids=($(eoldpids))
929 if (( ! ${#oldpids[@]} )); then
930 return
931 fi
932 # print the date every 20 iterations
933 if (( ! count % 20 )); then
934 date
935 fi
936 count+=1
937 ps -f -p "${oldpids[*]}"
938 sleep 1
939 done
940 }
941
942 eless() {
943 less /var/log/exim4/mainlog
944 }
945 ccomp less eless
946 eqcat() {
947 exiqgrep -ir.\* -o 60 | while read -r i; do
948 hlm exim -Mvc $i
949 echo
950 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
951 done
952 }
953 eqrmf() {
954 # other ways to get the list of message ids:
955 # exim -bp | awk 'NF == 4 {print $3}'
956 # # this is slower 160ms, vs 60.
957 # exipick -i
958 exiqgrep -ir.\* | xargs exim -Mrm
959 }
960
961 econfdevnew() {
962 rm -rf /tmp/edev
963 mkdir -p /tmp/edev/etc
964 cp -ra /etc/exim4 /tmp/edev/etc
965 cp -ra /etc/alias* /tmp/edev/etc
966 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
967 econfdev
968 }
969 econfdev() {
970 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
971 }
972
973
974
975
976 fa() {
977 # find array. make an array of file names found by find into $x
978 # argument: find arguments
979 # return: find results in an array $x
980 while read -rd ''; do
981 x+=("$REPLY");
982 done < <(find "$@" -print0);
983 }
984
985 faf() { # find all files. use -L to follow symlinks
986 find "$@" -not \( -name .svn -prune -o -name .git -prune \
987 -o -name .hg -prune -o -name .editor-backups -prune \
988 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
989 }
990
991 # full path without resolving symlinks
992 fp() {
993 local dir base
994 base="${1##*/}"
995 dir="${1%$base}"
996 printf "%s/%s\n" $(cd $dir; pwd) "$base"
997 }
998
999
1000 # mail related
1001 frozen() {
1002 rm -rf /tmp/frozen
1003 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
1004 sudo exim -Mvl $id
1005 echo
1006 sudo exim -Mvh $id
1007 echo
1008 sudo exim -Mvb $id
1009 echo -e '\n\n##############################\n'
1010 done | tee -a /tmp/frozen
1011 }
1012 frozenrm() {
1013 local ids=()
1014 while read -r line; do
1015 printf '%s\n' "$line"
1016 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
1017 done < <(s mailq)
1018 echo "sleeping for 2 in case you change your mind"
1019 sleep 2
1020 sudo exim -Mrm "${ids[@]}"
1021 }
1022
1023 funce() {
1024 # like -e for functions. returns on error.
1025 # at the end of the function, disable with:
1026 # trap ERR
1027 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
1028 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
1029 trap ERR
1030 return' ERR
1031 }
1032
1033 getdir () {
1034 local help="Usage: getdir [--help] PATH
1035 Output the directory of PATH, or just PATH if it is a directory."
1036 if [[ $1 == --help ]]; then
1037 echo "$help"
1038 return 0
1039 fi
1040 if [[ $# -ne 1 ]]; then
1041 echo "getdir error: expected 1 argument, got $#"
1042 return 1
1043 fi
1044 if [[ -d $1 ]]; then
1045 echo "$1"
1046 else
1047 local dir
1048 dir="$(dirname "$1")"
1049 if [[ -d $dir ]]; then
1050 echo "$dir"
1051 else
1052 echo "getdir error: directory does not exist"
1053 return 1
1054 fi
1055 fi
1056 }
1057
1058 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
1059 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
1060 local root
1061 root=$(gitroot) || return 1 # function to set gitroot
1062 builtin cd "$root"
1063 git symbolic-ref HEAD refs/heads/$1
1064 rm .git/index
1065 git clean -fdx
1066 }
1067
1068 # shellcheck disable=SC2120
1069 gitroot() {
1070 local help="Usage: gitroot [--help]
1071 Print the full path to the root of the current git repo
1072
1073 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
1074 and works in older versions of git which did not have that."
1075 if [[ $1 == --help ]]; then
1076 echo "$help"
1077 return
1078 fi
1079 local p
1080 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
1081 [[ $p != /* ]] && p=$PWD
1082 echo "${p%%/.git}"
1083 }
1084
1085 g() {
1086
1087 # todo: patch emacs so it will look elsewhere. this is kinda sad:
1088 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
1089
1090 local args gdb=false
1091
1092 if [[ $EMACSDIR ]]; then
1093 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
1094 fi
1095
1096 if [[ $DISPLAY ]]; then
1097 args=-n
1098 fi
1099
1100 if (( $# == 0 )); then
1101 args+=" -c"
1102 fi
1103 # duplicate -c, but oh well
1104 if ! pgrep -u $EUID emacsclient; then
1105 if (( $# == 0 )) && type -p gdb &>/dev/null; then
1106 gdb=true
1107 else
1108 args+=" -c"
1109 fi
1110 fi
1111 if [[ $EMACSDIR ]]; then
1112 # Alter the path here, otherwise the nfs mount gets triggered on the
1113 # first path lookup when emacs is not being used.
1114 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
1115 else
1116 if $gdb; then
1117 # due to a bug, we cant debug from the start unless we get a new gdb
1118 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
1119 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
1120 m emacsclient -a "" $args "$@"
1121 sleep 1
1122 cd /a/opt/emacs-$(distro-name)$(distro-num)
1123 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
1124 cd -
1125 else
1126 m emacsclient -a "" $args "$@"
1127 fi
1128 fi
1129 }
1130
1131 # force terminal version
1132 gn() {
1133 g -n "$@"
1134 }
1135
1136 gmacs() {
1137 # quit will prompt if the program crashes.
1138 gdb -ex=r -ex=quit --args emacs "$@"; r;
1139 }
1140
1141 gdkill() {
1142 # kill the emacs daemon
1143 pk1 emacs --daemon
1144 }
1145
1146 gr() {
1147 grep -iIP --color=auto "$@" || return $?
1148 }
1149 grr() { # grep recursive
1150 # Don't return 1 on nonmatch because this is meant to be
1151 # interactive, not in a conditional.
1152 if [[ ${#@} == 1 ]]; then
1153 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
1154 else
1155 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
1156 fi
1157 }
1158 ccomp grep gr grr
1159
1160 rg() { grr "$@"; }
1161 ccomp grep rg
1162
1163 hr() { # horizontal row. used to break up output
1164 printf "$(tput setaf 5 2>/dev/null ||:)â–ˆ$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
1165 echo
1166 }
1167 # highlight
1168 hl() {
1169 local col input_len=0
1170 for arg; do
1171 input_len=$((input_len + 1 + ${#arg}))
1172 done
1173 col=$((60 - input_len))
1174 printf "\e[1;97;41m%s" "$*"
1175 if (( col > 0 )); then
1176 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
1177 fi
1178 echo
1179 }
1180 hlm() { hl "$*"; "$@"; }
1181
1182 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
1183
1184
1185 # get latest hub and run it
1186 # main command to use:
1187 # hub pull-request --no-edit
1188 # --no-edit means to use the first commit\'s message as the pull request message.
1189 # If that fails, try doing
1190 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
1191 # where branch is usually master. it does the pr against your current branch.
1192 #
1193 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1194 # it\'s at ~/.config/hub
1195 hub() {
1196 local up uptar updir p
1197 p=/github/hub/releases/
1198 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
1199 uptar=${up##*/}
1200 updir=${uptar%.tgz}
1201 if [[ ! -e /a/opt/$updir ]]; then
1202 rm -rf /a/opt/hub-linux-amd64*
1203 wget -P /a/opt $up
1204 tar -C /a/opt -zxf /a/opt/$uptar
1205 rm -f /a/opt/$uptar
1206 fi
1207 if ! which hub &>/dev/null; then
1208 sudo /a/opt/$updir/install
1209 fi
1210
1211 # save token across computers
1212 if [[ ! -L ~/.config/hub ]]; then
1213 if [[ -e ~/.config/hub ]]; then
1214 mv ~/.config/hub /p/c/subdir_files/.config/
1215 fi
1216 if [[ -e /p/c/subdir_files/.config/hub ]]; then
1217 conflink
1218 fi
1219 fi
1220 command hub "$@"
1221 }
1222
1223 i() { git "$@"; }
1224 ccomp git i
1225
1226 ic() {
1227 # fast commit all
1228 git commit -am "$*"
1229 }
1230
1231 ipp() {
1232 git pull
1233 git push
1234 }
1235
1236
1237 ifn() {
1238 # insensitive find
1239 # -L = follow symlinks
1240 find -L . -not \( -name .svn -prune -o -name .git -prune \
1241 -o -name .hg -prune -o -name .editor-backups -prune \
1242 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1243 }
1244
1245 ifd() {
1246 # insensitive find directory
1247 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
1248 -o -name .hg -prune -o -name .editor-backups -prune \
1249 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1250 }
1251
1252
1253 ipdrop() {
1254 sudo iptables -A INPUT -s $1 -j DROP
1255 }
1256
1257
1258 istext() {
1259 grep -Il "" "$@" &>/dev/null
1260 }
1261
1262 jtail() {
1263 journalctl -n 10000 -f "$@"
1264 }
1265 jr() { journalctl "$@" ; }
1266 jrf() { journalctl -f "$@" ; }
1267 jru() {
1268 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
1269 }
1270
1271 l() {
1272 if [[ $PWD == /[iap] ]]; then
1273 command ls -A --color=auto -I lost+found "$@"
1274 else
1275 command ls -A --color=auto "$@"
1276 fi
1277 }
1278
1279 lcn() { locate -i "*$**"; }
1280
1281 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
1282
1283 lt() { ll -tr "$@"; }
1284
1285 lld() { ll -d "$@"; }
1286
1287 ccomp ls l lg lt lld ll
1288
1289 # low recursively
1290 lowr() {
1291 local f dirs i a
1292 local -a all
1293 for dirs in false true; do
1294 for f; do
1295 if [[ -d $f ]]; then
1296 all=("$f"/**)
1297 # reverse the order to rename the nested dirs first.
1298 # note: 0 element is the dir itself
1299 for ((i=${#all[@]}-1; i>=1; i--)); do
1300 a="${all[i]}"
1301 if $dirs && [[ -d $a ]]; then
1302 # e dirs low "$a" # debug
1303 low "$a"
1304 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1305 # debug
1306 # e not dirs low "$a" # debug
1307 low "$a"
1308 fi
1309 done
1310 fi
1311 # just rename all the top level args on the second pass
1312 if $dirs; then
1313 # e final dirs low "$f" # debug
1314 low "$f"
1315 fi
1316 done
1317 done
1318 }
1319
1320 low() { # make filenames lowercase, remove bad chars
1321 local arg new dir f
1322 for arg; do
1323 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1324 dir="${arg%/*}"
1325 if (( ${#dir} == ${#arg} )); then
1326 dir=.
1327 fi
1328 f="${arg##*/}"
1329 new="${f,,}" # downcase
1330 new="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1331 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1332 new="${new%"${new##*[[:alnum:]]}"}"
1333 # remove bad underscores, like __ and _._
1334 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1335 safe_rename "$dir/$f" "$dir/$new" || return 1
1336 done
1337 return 0
1338 }
1339
1340 lower() { # make first letter of filenames lowercase.
1341 local x
1342 for x in "$@"; do
1343 if [[ ${x::1} == [A-Z] ]]; then
1344 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1345 safe_rename "$x" "$y" || return 1
1346 fi
1347 done
1348 }
1349
1350
1351 k() { # history search
1352 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1353 }
1354 ks() { # history search with context
1355 # args are an extended regex used by sed
1356 history | sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" | tail -n 80 || [[ $? == 1 ]];
1357 }
1358 ksu() { # history search unique
1359 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1360 }
1361
1362 # todo: id like to do maybe a daily or hourly cronjob to
1363 # check that my history file size is increasing. Ive had it
1364 # inexplicably truncated in the past.
1365 histrm() {
1366 history -n
1367 HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1368 read -p "press anything but contrl-c to delete"
1369 for entry in $(HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' | tac); do
1370 history -d $entry
1371 done
1372 history -w
1373 }
1374
1375 ccomp grep k ks ksu histrm
1376
1377
1378 make-targets() {
1379 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1380 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1381 }
1382
1383 mkc() {
1384 mkdir "$1"
1385 c "$1"
1386 }
1387 ccomp mkdir mkc
1388
1389 mkct() {
1390 mkc $(mktemp -d)
1391 }
1392
1393 mkt() { # mkdir and touch file
1394 local path="$1"
1395 mkdir -p "$(dirname "$path")"
1396 touch "$path"
1397 }
1398
1399 # shellcheck disable=SC2032
1400 mkdir() { command mkdir -p "$@"; }
1401
1402 nags() {
1403 # https://github.com/HenriWahl/Nagstamon/issues/357
1404 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1405 /usr/lib/notification-daemon/notification-daemon &
1406 fi
1407 /usr/bin/nagstamon &
1408 }
1409
1410 nmt() {
1411 # cant use s because sudo -i doesnt work for passwordless sudo command
1412 case $EUID in
1413 0)
1414 sudo nmtui-connect "$@"
1415 ;;
1416 *)
1417 nmtui-connect "$@"
1418 ;;
1419 esac
1420 }
1421
1422 nopanic() {
1423 # shellcheck disable=SC2024
1424 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1425 }
1426
1427 p8() { ping "$@" 8.8.8.8; }
1428 p6() { ping6 "$@" 2001:4860:4860::8888; }
1429
1430 pkx() { # package extract
1431 local pkg cached tmp f
1432 c $(mktemp -d)
1433 pkg=$1
1434 # shellcheck disable=SC2012
1435 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1436 if [[ $cached ]]; then
1437 cp $cached .
1438 else
1439 aptitude download $pkg || return 1
1440 fi
1441 tmp=(*); f=${tmp[0]} # only 1 expected
1442 ex $f
1443 rm -f $f
1444 }
1445
1446 # pgrep and kill
1447 pk1() {
1448 local pid
1449 pid=($(pgrep -f "$*"))
1450 case ${#pid[@]} in
1451 1)
1452 # shellcheck disable=SC2128
1453 {
1454 ps -F $pid
1455 m kill $pid
1456 }
1457 ;;
1458 0) echo "no pid found" ;;
1459 *)
1460 ps -F ${pid[@]}
1461 ;;
1462 esac
1463 }
1464
1465 psg () {
1466 local x y help
1467 help="Usage: psg [--help] GREP_ARGS
1468 grep ps and output in a nice format"
1469 if [[ $1 == --help ]]; then
1470 echo "$help"
1471 return
1472 fi
1473 x=$(ps -eF)
1474 # final grep is because some commands tend to have a lot of trailing spaces
1475 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1476 if [[ $y ]]; then
1477 echo "$x" | head -n 1 || [[ $? == 141 ]]
1478 echo "$y"
1479 fi
1480 }
1481
1482 pubip() { curl -4s https://icanhazip.com; }
1483 pubip6() { curl -6s https://icanhazip.com; }
1484 whatismyip() { pubip; }
1485
1486
1487 q() { # start / launch a program in the backround and redir output to null
1488 "$@" &> /dev/null &
1489 }
1490
1491 # shellcheck disable=SC2120
1492 r() {
1493 if [[ $HISTFILE ]]; then
1494 history -a # save history
1495 fi
1496 trap ERR # this avoids a segfault
1497 exit ${1:0}
1498 # i had this redir, not sure why
1499 # exit "$@" 2>/dev/null
1500 }
1501
1502 # scp is insecure and deprecated.
1503 scp() {
1504 rsync --inplace "$@"
1505 }
1506
1507 randport() {
1508 # available high ports are 1024-65535,
1509 # but lets skip things that are more likely to be in use
1510 python3 <<'EOF'
1511 import secrets
1512 print(secrets.SystemRandom().randrange(10002,65500))
1513 EOF
1514 }
1515
1516 # reapply bashrc
1517 reb() {
1518 source ~/.bashrc
1519 }
1520
1521 rl() {
1522 readlink -f "$@"
1523 }
1524 ccomp readlink rl
1525
1526 rsd() {
1527 # rsync, root is required to keep permissions right.
1528 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1529 # --no-times --delete
1530 # basically, make an exact copy, use checksums instead of file times to be more accurate
1531 rsync -ahvic --delete "$@"
1532 }
1533 rsa() {
1534 # like rlu, but dont delete files on the target end which
1535 # do not exist on the original end.
1536 rsync -ahvic "$@"
1537 }
1538 rst() {
1539 # rl without preserving modification time.
1540 rsync -ahvic --delete --no-t "$@"
1541 }
1542 rsu() { # [OPTS] HOST PATH
1543 # eg. rlu -opts frodo /testpath
1544 # relative paths will expanded with readlink -f.
1545 opts=("${@:1:$#-2}") # 1 to last -2
1546 path="${*:$#}" # last
1547 host="${*:$#-1:1}" # last -1
1548 if [[ $path == .* ]]; then
1549 path=$(readlink -f $path)
1550 fi
1551 # rync here uses checksum instead of time so we dont mess with
1552 # unison relying on time as much. g is for group, same reason
1553 # to keep up with unison.
1554 m s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1555 }
1556 ccomp rsync rsd rsa rst rsu
1557
1558 # find programs listening on a port
1559 ssp() {
1560 local port=$1
1561 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
1562 s ss -lpn state listening sport = $port
1563 }
1564
1565 resolvcat() {
1566 local f
1567 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1568 m s nscd -i hosts
1569 fi
1570 f=/etc/resolv.conf
1571 echo $f:; ccat $f
1572 hr; s ss -lpn sport = 53
1573 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1574 # this will fail is dnsmasq is failed
1575 hr; m ser status dnsmasq | cat || :
1576 f=/etc/dnsmasq.conf
1577 hr; echo $f:; ccat $f
1578 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1579 f=/etc/dnsmasq-servers.conf
1580 hr; echo $f:; ccat $f
1581 fi
1582 hr
1583 echo /etc/nsswitch.conf:
1584 grep '^ *hosts:' /etc/nsswitch.conf
1585 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1586 hr; m ser status systemd-resolved | cat || :
1587 hr; m resolvectl status | cat
1588 fi
1589
1590 }
1591 rcat() {
1592 resolvcat | less
1593 }
1594 reresolv() {
1595 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1596 m ser stop nscd
1597 sleep .5
1598 m ser start nscd
1599 m sudo nscd -i hosts
1600 fi
1601 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1602 m sudo systemctl restart dnsmasq
1603 fi
1604 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1605 m sudo systemctl restart systemd-resolved
1606 fi
1607 if type -P resolvectl &>/dev/null; then
1608 resolvectl flush-caches
1609 fi
1610 }
1611
1612 rmstrips() {
1613 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1614 }
1615
1616 sudo () {
1617 command sudo "$@" || return $?
1618 DID_SUDO=true
1619 }
1620 s() {
1621 # background
1622 # I use a function because otherwise we cant use in a script,
1623 # cant assign to variable.
1624 #
1625 # note: gksudo is recommended for X apps because it does not set the
1626 # home directory to the same, and thus apps writing to ~ fuck things up
1627 # with root owned files.
1628 #
1629 if [[ $EUID != 0 || $1 == -* ]]; then
1630 # shellcheck disable=SC2034
1631 SUDOD="$PWD" command sudo -i "$@"
1632 DID_SUDO=true
1633 else
1634 "$@"
1635 fi
1636 }
1637 sb() { # sudo bash -c
1638 # use sb instead of s is for sudo redirections,
1639 # eg. sb 'echo "ok fine" > /etc/file'
1640 # shellcheck disable=SC2034
1641 local SUDOD="$PWD"
1642 sudo -i bash -c "$@"
1643 }
1644 ccomp sudo s sb
1645
1646 safe_rename() { # warn and dont rename if file exists.
1647 # mv -n exists, but it\'s silent
1648 if [[ $# != 2 ]]; then
1649 echo safe_rename error: $# args, need 2 >2
1650 return 1
1651 fi
1652 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1653 if [[ -e $2 || -L $2 ]]; then
1654 echo "Cannot rename $1 to $2 as it already exists."
1655 else
1656 mv -vi "$1" "$2"
1657 fi
1658 fi
1659 }
1660
1661
1662 sd() {
1663 sudo dd status=none of="$1"
1664 }
1665
1666 ser() {
1667 if type -p systemctl &>/dev/null; then
1668 s systemctl "$@"
1669 else
1670 if (( $# >= 3 )); then
1671 echo iank: ser expected 2 or less arguments
1672 return 1
1673 fi
1674 s service $2 $1
1675 fi
1676 }
1677 serstat() {
1678 systemctl -n 40 status "$@"
1679 }
1680
1681 seru() { systemctl --user "$@"; }
1682 # like restart, but do nothing if its not already started
1683 srestart() {
1684 local service=$1
1685 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1686 systemctl restart $service
1687 fi
1688 }
1689
1690 setini() { # set a value in a .ini style file
1691 key="$1" value="$2" section="$3" file="$4"
1692 if [[ -s $file ]]; then
1693 sed -ri -f - "$file" <<EOF
1694 # remove existing keys
1695 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1696 # add key
1697 /^\s*\[$section\]/a $key=$value
1698 # from section to eof, do nothing
1699 /^\s*\[$section\]/,\$b
1700 # on the last line, if we haven't found section yet, add section and key
1701 \$a [$section]\\
1702 $key=$value
1703 EOF
1704 else
1705 cat >"$file" <<EOF
1706 [$section]
1707 $key=$value
1708 EOF
1709 fi
1710 }
1711
1712 sgo() { # service go
1713 service=$1
1714 ser restart $service || return 1
1715 if type -p systemctl &>/dev/null; then
1716 ser enable $service
1717 fi
1718 }
1719 soff () {
1720 for service; do
1721 # ignore services that dont exist
1722 if systemctl cat $service &>/dev/null; then
1723 ser stop $service;
1724 ser disable $service
1725 fi
1726 done
1727 }
1728
1729 sgu() {
1730 systemctl list-unit-files | rg "$@"
1731 }
1732
1733
1734 sk() {
1735
1736
1737 # disable a warning with:
1738 # shellcheck disable=SC2206 # reasoning
1739
1740 # see bash-template/style-guide.md for justifications
1741
1742 local quotes others
1743 quotes=2048,2068,2086,2206
1744 others=2029,2033,2054,2164
1745 shellcheck -W 999 -x -e $quotes,$others "$@" || return $?
1746 }
1747
1748
1749 # sl: ssh, but firsh rsync our bashrc and related files to a special
1750 # directory on the remote host if needed.
1751
1752 # Some environment variables and files need to be setup for this to work
1753 # (mine are set at the beginning of this file)
1754
1755 # SL_FILES_DIR: Environment variable. Path to folder which should at
1756 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1757 # remote hosts (top level symlinks are resolved) unless the host already
1758 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1759 # control and sync files to separately and already has the ~/.bashrc you
1760 # want. The remote bash will also take its .inputrc config from this
1761 # folder (default of not existing is fine). Mine looks like this:
1762 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1763
1764 # SL_INFO_DIR: Environment variable. This folder stores info about what
1765 # we detected on the remote system and when we last synced. It will be created
1766 # if it does not exist. Sometimes you may want to forget about a
1767 # remote system, you can use sl --rsync, or the function for that slr
1768 # below.
1769
1770 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1771 # depending on the remote host. Run this string on the remote host the
1772 # first time sl is run (or if we run slr). The result is passed to
1773 # SL_TEST_HOOK. For example,
1774 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1775
1776 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1777 # $SL_FILES_DIR to vary the files synced.
1778
1779 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1780 # example to exclude files within a directory. Note, excluded
1781 # files wont be deleted on rsync, you can add --delete-excluded
1782 # to the rsync command if that is desired.
1783
1784 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1785
1786 # For when ~/.bashrc is already customized on the remote server, you
1787 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1788 # commands, even in scripts. This paragraph is all about that. bash
1789 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1790 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1791 # and if you customize it, probably has bugs from time to time. This is
1792 # bad. Here's how I fix it. I have a special condition to "return" in my
1793 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1794 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1795 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1796 # separate file because even if I return early on, the whole file gets
1797 # parsed which can fail if there is a syntax error.
1798 sl() {
1799 # Background on LC_USEBASHRC var (no need to read if you just want to
1800 # use this function): env variables sent across ssh are strictly
1801 # limited, but we get LC_* at least in debian based machines, so we
1802 # just make that * be something no normal program would use. Note, on
1803 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1804 # set, and the inner shell also allows running a nondefault
1805 # .bashrc. This means the outer shell still ran the default .bashrc,
1806 # but that is the best we can do.
1807
1808 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1809 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1810 declare -a args tmpa
1811
1812 args=($SL_SSH_ARGS)
1813
1814 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1815 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1816 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1817 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
1818 # [command]
1819
1820 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
1821 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
1822 # [-F configfile] [-I pkcs11] [-i identity_file]
1823 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
1824 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
1825 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
1826
1827 force_rsync=false
1828 if [[ $1 == --rsync ]]; then
1829 force_rsync=true
1830 shift
1831 fi
1832
1833 sl_test_cmd=$SL_TEST_CMD
1834 sl_test_hook=$SL_TEST_HOOK
1835 sl_rsync_args=$SL_RSYNC_ARGS
1836 while [[ $1 ]]; do
1837 case "$1" in
1838 --rsync)
1839 force_rsync=true
1840 ;;
1841 --sl-test-cmd)
1842 sl_test_cmd="$2"
1843 shift
1844 ;;
1845 --sl-test-hook)
1846 sl_test_hook="$2"
1847 shift
1848 ;;
1849 --sl-rsync-args)
1850 sl_rsync_args="$2"
1851 shift
1852 ;;
1853 *)
1854 break
1855 ;;
1856 esac
1857 shift
1858 done
1859
1860 while [[ $1 ]]; do
1861 case "$1" in
1862 # note we dont support things like -4oOption
1863 -[46AaCfGgKkMNnqsTtVvXxYy]*)
1864 args+=("$1"); shift
1865 ;;
1866 -[bcDEeFIiJLlmOopQRSWw]*)
1867 # -oOption etc is valid
1868 if (( ${#1} >= 3 )); then
1869 args+=("$1"); shift
1870 else
1871 args+=("$1" "$2"); shift 2
1872 fi
1873 ;;
1874 *)
1875 break
1876 ;;
1877 esac
1878 done
1879 remote="$1"
1880 if [[ ! $remote ]]; then
1881 echo $0: error hostname required >&2
1882 return 1
1883 fi
1884 shift
1885
1886 if [[ ! $SL_INFO_DIR ]]; then
1887 echo error: missing '$SL_INFO_DIR' env var >&2
1888 return 1
1889 fi
1890
1891 dorsync=false
1892 haveinfo=false
1893 tmpa=($SL_INFO_DIR/???????????"$remote")
1894 sshinfo=${tmpa[0]}
1895 if [[ -e $sshinfo ]]; then
1896 if $force_rsync; then
1897 rm -f $sshinfo
1898 else
1899 haveinfo=true
1900 fi
1901 fi
1902 if $haveinfo; then
1903 tmp=${sshinfo[0]##*/}
1904 tmp2=${tmp::11}
1905 type=${tmp2: -1}
1906 extra_info=$(cat $sshinfo)
1907 else
1908 # we test for string to know ssh succeeded
1909 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
1910 testcmd="if $testbool; then printf y; else printf n; fi"
1911 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
1912 echo failed sl test. doing plain ssh -v
1913 command ssh -v "${args[@]}" "$remote"
1914 fi
1915 if [[ $tmp == y* ]]; then
1916 type=a
1917 else
1918 dorsync=true
1919 type=b
1920 fi
1921 extra_info="${tmp:1}"
1922 fi
1923 if [[ $sl_test_hook ]]; then
1924 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
1925 fi
1926
1927 if $haveinfo && [[ $type == b ]]; then
1928 info_sec=${tmp::10}
1929 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
1930 files_sec=${files_sec%%.*}
1931 if (( files_sec > info_sec )); then
1932 dorsync=true
1933 rm -f $sshinfo
1934 fi
1935 fi
1936
1937 sync_dirname=${SL_FILES_DIR##*/}
1938
1939 if [[ ! $SL_FILES_DIR ]]; then
1940 echo error: missing '$SL_FILES_DIR' env var >&2
1941 return 1
1942 fi
1943
1944 if $dorsync; then
1945 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
1946 fi
1947 if $dorsync || ! $haveinfo; then
1948 sshinfo=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
1949 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
1950 printf "%s\n" "$extra_info" >$sshinfo
1951 chmod 666 $sshinfo
1952 fi
1953 if [[ $type == b ]]; then
1954 if (( ${#@} )); then
1955 # Theres a couple ways to pass arguments, im not sure whats best,
1956 # but relying on bash 4.4+ escape quoting seems most reliable.
1957 command ssh "${args[@]}" "$remote" \
1958 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
1959 elif [[ ! -t 0 ]]; then
1960 # This case is when commands are being piped to ssh.
1961 # Normally, no bashrc gets sourced.
1962 # But, since we are doing all this, lets source it because we can.
1963 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1964 else
1965 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
1966 fi
1967 else
1968 if [[ -t 0 ]]; then
1969 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
1970 else
1971 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1972 fi
1973 fi
1974 # this function inspired from https://github.com/Russell91/sshrc
1975 }
1976
1977 slr() {
1978 sl --rsync "$@"
1979 }
1980 sss() { # ssh solo
1981 sl -oControlMaster=no -oControlPath=/ "$@"
1982 }
1983 # kill off old shared socket then ssh
1984 ssk() {
1985 m ssh -O exit "$@" || [[ $? == 255 ]]
1986 m sl "$@"
1987 }
1988 ccomp ssh sl slr sss ssk
1989 # plain ssh
1990 ssh() {
1991 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
1992 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
1993 else
1994 LC_USEBASHRC=t command ssh "$@"
1995 fi
1996 }
1997
1998
1999 slog() {
2000 # log with script. timing is $1.t and script is $1.s
2001 # -l to save to ~/typescripts/
2002 # -t to add a timestamp to the filenames
2003 local logdir do_stamp arg_base
2004 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
2005 logdir="/a/dt/"
2006 do_stamp=false
2007 while getopts "lt" option
2008 do
2009 case $option in
2010 l ) arg_base=$logdir ;;
2011 t ) do_stamp=true ;;
2012 esac
2013 done
2014 shift $((OPTIND - 1))
2015 arg_base+=$1
2016 [[ -e $logdir ]] || mkdir -p $logdir
2017 $do_stamp && arg_base+=$(date +%F.%T%z)
2018 script -t $arg_base.s 2> $arg_base.t
2019 }
2020 splay() { # script replay
2021 #logRoot="$HOME/typescripts/"
2022 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2023 scriptreplay "$1.t" "$1.s"
2024 }
2025
2026 sr() {
2027 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2028 if [[ $# == 0 ]]; then
2029 sudo -E bash -c -l "$(history -p '!!')"
2030 else
2031 echo this command redos last history item. no argument is accepted
2032 fi
2033 }
2034
2035 srm () {
2036 # with -ll, less secure but faster.
2037 command srm -ll "$@"
2038 }
2039
2040 srun() {
2041 scp $2 $1:/tmp
2042 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
2043 }
2044
2045
2046 swap() {
2047 local tmp
2048 tmp=$(mktemp)
2049 mv $1 $tmp
2050 mv $2 $1
2051 mv $tmp $2
2052 }
2053
2054 tclock() { # terminal clock
2055 local x
2056 clear
2057 date +%l:%_M
2058 len=60
2059 # this goes to full width
2060 #len=${1:-$((COLUMNS -7))}
2061 x=1
2062 while true; do
2063 if (( x == len )); then
2064 end=true
2065 d="$(date +%l:%_M) "
2066 else
2067 end=false
2068 d=$(date +%l:%M:%_S)
2069 fi
2070 echo -en "\r"
2071 echo -n "$d"
2072 for ((i=0; i<x; i++)); do
2073 if (( i % 6 )); then
2074 echo -n _
2075 else
2076 echo -n .
2077 fi
2078 done
2079 if $end; then
2080 echo
2081 x=1
2082 else
2083 x=$((x+1))
2084 fi
2085 sleep 5
2086 done
2087 }
2088
2089
2090 te() {
2091 # test existence / exists
2092 local ret=0
2093 for x in "$@"; do
2094 [[ -e "$x" || -L "$x" ]] || ret=1
2095 done
2096 return $ret
2097 }
2098
2099 psoff() {
2100 # normally, i would just execute these commands in the function.
2101 # however, DEBUG is not inherited, so we need to run it outside a function.
2102 # And we want to run set -x afterwards to avoid spam, so we cram everything
2103 # in here, and then it will run after this function is done.
2104 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
2105 }
2106 pson() {
2107 PROMPT_COMMAND=prompt-command
2108 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2109 trap 'settitle "$BASH_COMMAND"' DEBUG
2110 fi
2111 }
2112
2113 tx() { # toggle set -x, and the prompt so it doesnt spam
2114 if [[ $- == *x* ]]; then
2115 set +x
2116 pson
2117 else
2118 psoff
2119 fi
2120 }
2121
2122 psnetns() {
2123 # show all processes in the network namespace $1.
2124 # blank entries appear to be subprocesses/threads
2125 local x netns
2126 netns=$1
2127 ps -w | head -n 1
2128 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
2129 while read -r l; do
2130 x=$(ps -w --no-headers -p $l);
2131 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2132 done
2133 }
2134 nonet() {
2135 if ! s ip netns list | grep -Fx nonet &>/dev/null; then
2136 s ip netns add nonet
2137 fi
2138 sudo -E env /sbin/ip netns exec nonet sudo -E -u iank /bin/bash
2139 }
2140
2141 m() { printf "%s\n" "$*"; "$@"; }
2142
2143 uptime() {
2144 if type -p uprecords &>/dev/null; then
2145 uprecords -B
2146 else
2147 command uptime
2148 fi
2149 }
2150
2151 virshrm() {
2152 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
2153 }
2154
2155 vm-set-listen(){
2156 local t
2157 t=$(mktemp)
2158 local vm=$1
2159 local ip=$2
2160 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2161 sed -r "s/listen='[^']+/listen='$ip/"> $t
2162 sudo virsh undefine $vm
2163 sudo virsh define $t
2164 }
2165
2166
2167 vmshare() {
2168 vm-set-listen $1 0.0.0.0
2169 }
2170
2171
2172 vmunshare() {
2173 vm-set-listen $1 127.0.0.1
2174 }
2175
2176 myiwscan() {
2177 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2178 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2179 sudo iw dev wls1 scan | sed -rn "
2180 s/^\Wcapability: (.*)/\1/;Ta;h;b
2181 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2182 # padded to min width of 20
2183 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2184 "|sort -r
2185 }
2186
2187 # Run script by copying it to a temporary location first,
2188 # and changing directory, so we don't have any open
2189 # directories or files that could cause problems when
2190 # remounting.
2191 z() {
2192 local tmp
2193 tmp=$(type -p "$1")
2194 if [[ $tmp ]]; then
2195 cd $(mktemp -d)
2196 cp -a "$tmp" .
2197 shift
2198 ./"${tmp##*/}" "$@"
2199 else
2200 "$@"
2201 fi
2202 }
2203
2204 # * misc stuff
2205
2206
2207 if $use_color && type -p tput &>/dev/null; then
2208 term_bold="$(tput bold)"
2209 term_red="$(tput setaf 1)"
2210 term_green="$(tput setaf 2)"
2211 term_yellow="$(tput setaf 3)"
2212 term_purple="$(tput setaf 5)"
2213 term_nocolor="$(tput sgr0)" # no font attributes
2214
2215 # unused so far. commented for shellcheck
2216 # term_underl="$(tput smul)"
2217 # term_blue="$(tput setaf 4)"
2218 # term_cyan="$(tput setaf 6)"
2219 fi
2220 # Try to keep environment pollution down, EPA loves us.
2221 unset safe_term match_lhs use_color
2222
2223 # * prompt
2224
2225
2226 if [[ $- == *i* ]]; then
2227
2228
2229 case $HOSTNAME in
2230 bk|je|li)
2231 if [[ $EUID == 1000 ]]; then
2232 system-status _ ||:
2233 fi
2234 ;;
2235 esac
2236
2237
2238 # this needs to come before next ps1 stuff
2239 # this stuff needs bash 4, feb 2009,
2240 # old enough to no longer condition on $BASH_VERSION anymore
2241 shopt -s autocd
2242 shopt -s dirspell
2243 PS1='\w'
2244 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2245 PROMPT_DIRTRIM=2
2246 bind -m vi-command B:shell-backward-word
2247 bind -m vi-command W:shell-forward-word
2248 fi
2249
2250 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2251 unset PROMPT_DIRTRIM
2252 PS1="\h:$PS1"
2253 fi
2254
2255 # emacs terminal has problems if this runs slowly,
2256 # so I've thrown a bunch of things at the wall to speed it up.
2257 prompt-command() {
2258 local return=$? # this MUST COME FIRST
2259 local ps_char ps_color
2260 unset IFS
2261
2262 if [[ $HISTFILE ]]; then
2263 history -a # save history
2264 fi
2265
2266 # assigned in brc2
2267 # shellcheck disable=SC1303
2268 if [[ $jr_pid ]]; then
2269 if [[ -e /proc/$jr_pid ]]; then
2270 kill $jr_pid
2271 fi
2272 unset jr_pid
2273 fi
2274
2275 case $return in
2276 0) ps_color="$term_purple"
2277 ps_char='\$'
2278 ;;
2279 *) ps_color="$term_green"
2280 ps_char="$return \\$"
2281 ;;
2282 esac
2283 if [[ ! -O . ]]; then # not owner
2284 if [[ -w . ]]; then # writable
2285 ps_color="$term_bold$term_red"
2286 else
2287 ps_color="$term_bold$term_green"
2288 fi
2289 fi
2290
2291 # faster than sourceing the file im guessing
2292 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2293 eval $(< /dev/shm/iank-status)
2294 fi
2295 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2296 ps_char="@ $ps_char"
2297 fi
2298 # We could test if sudo is active with sudo -nv
2299 # but then we get an email and log of lots of failed sudo commands.
2300 # We could turn those off, but seems better not to.
2301 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2302 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2303 fi
2304 if [[ ! $HISTFILE ]]; then
2305 ps_char="NOHIST $ps_char"
2306 fi
2307 PS1="${PS1%"${PS1#*[wW]}"} $psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2308
2309 # set titlebar. instead, using more advanced
2310 # titelbar below
2311 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2312 }
2313 PROMPT_COMMAND=prompt-command
2314
2315 if [[ $TERM == screen* ]]; then
2316 _title_escape="\033]..2;"
2317 else
2318 # somme sites recommend this, i dunno what the diff is.
2319 #_title_escape="\033]30;"
2320 _title_escape="\033]0;"
2321 fi
2322
2323 settitle () {
2324 # this makes it so we show the current command if
2325 # one is running, otherwise, show nothing
2326
2327 if [[ $1 == prompt-command ]]; then
2328 return 0
2329 fi
2330 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
2331 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2332 printf "%s" "$*"
2333 echo -ne "\007"
2334 fi
2335 }
2336
2337 # note, this wont work:
2338 # x=$(mktemp); cp a $x
2339 # I havnt figured out why, bigger fish to fry.
2340 #
2341 # for titlebar.
2342 # condition from the screen man page i think.
2343 # note: duplicated in tx()
2344 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2345 trap 'settitle "$BASH_COMMAND"' DEBUG
2346 else
2347 trap DEBUG
2348 fi
2349
2350 fi
2351
2352 # * stuff that makes sense to be at the end
2353
2354
2355 # best practice
2356 unset IFS
2357
2358 # shellcheck disable=SC1090
2359 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2360
2361 # I had this idea to start a bash shell which would run an initial
2362 # command passed through this env variable, then continue on
2363 # interactively. But the use case I had in mind went away.
2364 #
2365 # if [[ $MY_INIT_CMD ]]; then
2366 # "${MY_INIT_CMD[@]}"
2367 # unset MY_INIT_CMD
2368 # fi
2369
2370 # ensure no bad programs appending to this file will have an affect
2371 return 0