mostly t11 fixes
[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 find -L . -not \( -name .svn -prune -o -name .git -prune \
1240 -o -name .hg -prune -o -name .editor-backups -prune \
1241 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1242 }
1243
1244 ifd() {
1245 # insensitive find directory
1246 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
1247 -o -name .hg -prune -o -name .editor-backups -prune \
1248 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1249 }
1250
1251
1252 ipdrop() {
1253 sudo iptables -A INPUT -s $1 -j DROP
1254 }
1255
1256
1257 istext() {
1258 grep -Il "" "$@" &>/dev/null
1259 }
1260
1261 jtail() {
1262 journalctl -n 10000 -f "$@"
1263 }
1264 jr() { journalctl "$@" ; }
1265 jrf() { journalctl -f "$@" ; }
1266 jru() {
1267 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
1268 }
1269
1270 l() {
1271 if [[ $PWD == /[iap] ]]; then
1272 command ls -A --color=auto -I lost+found "$@"
1273 else
1274 command ls -A --color=auto "$@"
1275 fi
1276 }
1277
1278 lcn() { locate -i "*$**"; }
1279
1280 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
1281
1282 lt() { ll -tr "$@"; }
1283
1284 lld() { ll -d "$@"; }
1285
1286 ccomp ls l lg lt lld ll
1287
1288 # low recursively
1289 lowr() {
1290 local f dirs i a
1291 local -a all
1292 for dirs in false true; do
1293 for f; do
1294 if [[ -d $f ]]; then
1295 all=("$f"/**)
1296 # reverse the order to rename the nested dirs first.
1297 # note: 0 element is the dir itself
1298 for ((i=${#all[@]}-1; i>=1; i--)); do
1299 a="${all[i]}"
1300 if $dirs && [[ -d $a ]]; then
1301 # e dirs low "$a" # debug
1302 low "$a"
1303 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1304 # debug
1305 # e not dirs low "$a" # debug
1306 low "$a"
1307 fi
1308 done
1309 fi
1310 # just rename all the top level args on the second pass
1311 if $dirs; then
1312 # e final dirs low "$f" # debug
1313 low "$f"
1314 fi
1315 done
1316 done
1317 }
1318
1319 low() { # make filenames lowercase, remove bad chars
1320 local arg new dir f
1321 for arg; do
1322 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1323 dir="${arg%/*}"
1324 if (( ${#dir} == ${#arg} )); then
1325 dir=.
1326 fi
1327 f="${arg##*/}"
1328 new="${f,,}" # downcase
1329 new="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1330 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1331 new="${new%"${new##*[[:alnum:]]}"}"
1332 # remove bad underscores, like __ and _._
1333 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1334 safe_rename "$dir/$f" "$dir/$new" || return 1
1335 done
1336 return 0
1337 }
1338
1339 lower() { # make first letter of filenames lowercase.
1340 local x
1341 for x in "$@"; do
1342 if [[ ${x::1} == [A-Z] ]]; then
1343 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1344 safe_rename "$x" "$y" || return 1
1345 fi
1346 done
1347 }
1348
1349
1350 k() { # history search
1351 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1352 }
1353 ks() { # history search with context
1354 # args are an extended regex used by sed
1355 history | sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" | tail -n 80 || [[ $? == 1 ]];
1356 }
1357 ksu() { # history search unique
1358 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1359 }
1360
1361 # todo: id like to do maybe a daily or hourly cronjob to
1362 # check that my history file size is increasing. Ive had it
1363 # inexplicably truncated in the past.
1364 histrm() {
1365 history -n
1366 HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1367 read -p "press anything but contrl-c to delete"
1368 for entry in $(HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' | tac); do
1369 history -d $entry
1370 done
1371 history -w
1372 }
1373
1374 ccomp grep k ks ksu histrm
1375
1376
1377 make-targets() {
1378 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1379 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1380 }
1381
1382 mkc() {
1383 mkdir "$1"
1384 c "$1"
1385 }
1386 ccomp mkdir mkc
1387
1388 mkct() {
1389 mkc $(mktemp -d)
1390 }
1391
1392 mkt() { # mkdir and touch file
1393 local path="$1"
1394 mkdir -p "$(dirname "$path")"
1395 touch "$path"
1396 }
1397
1398 # shellcheck disable=SC2032
1399 mkdir() { command mkdir -p "$@"; }
1400
1401 nags() {
1402 # https://github.com/HenriWahl/Nagstamon/issues/357
1403 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1404 /usr/lib/notification-daemon/notification-daemon &
1405 fi
1406 /usr/bin/nagstamon &
1407 }
1408
1409 nmt() {
1410 s nmtui-connect "$@"
1411 }
1412
1413 nopanic() {
1414 # shellcheck disable=SC2024
1415 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1416 }
1417
1418 p8() { ping "$@" 8.8.8.8; }
1419 p6() { ping6 "$@" 2001:4860:4860::8888; }
1420
1421 pkx() { # package extract
1422 local pkg cached tmp f
1423 c $(mktemp -d)
1424 pkg=$1
1425 # shellcheck disable=SC2012
1426 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1427 if [[ $cached ]]; then
1428 cp $cached .
1429 else
1430 aptitude download $pkg || return 1
1431 fi
1432 tmp=(*); f=${tmp[0]} # only 1 expected
1433 ex $f
1434 rm -f $f
1435 }
1436
1437 # pgrep and kill
1438 pk1() {
1439 local pid
1440 pid=($(pgrep -f "$*"))
1441 case ${#pid[@]} in
1442 1)
1443 # shellcheck disable=SC2128
1444 {
1445 ps -F $pid
1446 m kill $pid
1447 }
1448 ;;
1449 0) echo "no pid found" ;;
1450 *)
1451 ps -F ${pid[@]}
1452 ;;
1453 esac
1454 }
1455
1456 psg () {
1457 local x y help
1458 help="Usage: psg [--help] GREP_ARGS
1459 grep ps and output in a nice format"
1460 if [[ $1 == --help ]]; then
1461 echo "$help"
1462 return
1463 fi
1464 x=$(ps -eF)
1465 # final grep is because some commands tend to have a lot of trailing spaces
1466 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1467 if [[ $y ]]; then
1468 echo "$x" | head -n 1 || [[ $? == 141 ]]
1469 echo "$y"
1470 fi
1471 }
1472
1473 pubip() { curl -4s https://icanhazip.com; }
1474 pubip6() { curl -6s https://icanhazip.com; }
1475 whatismyip() { pubip; }
1476
1477
1478 q() { # start / launch a program in the backround and redir output to null
1479 "$@" &> /dev/null &
1480 }
1481
1482 # shellcheck disable=SC2120
1483 r() {
1484 if [[ $HISTFILE ]]; then
1485 history -a # save history
1486 fi
1487 trap ERR # this avoids a segfault
1488 exit ${1:0}
1489 # i had this redir, not sure why
1490 # exit "$@" 2>/dev/null
1491 }
1492
1493 # scp is insecure and deprecated.
1494 scp() {
1495 rsync --inplace "$@"
1496 }
1497
1498 randport() {
1499 # available high ports are 1024-65535,
1500 # but lets skip things that are more likely to be in use
1501 python3 <<'EOF'
1502 import secrets
1503 print(secrets.SystemRandom().randrange(10002,65500))
1504 EOF
1505 }
1506
1507 # reapply bashrc
1508 reb() {
1509 source ~/.bashrc
1510 }
1511
1512 rl() {
1513 readlink -f "$@"
1514 }
1515 ccomp readlink rl
1516
1517 rsd() {
1518 # rsync, root is required to keep permissions right.
1519 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1520 # --no-times --delete
1521 # basically, make an exact copy, use checksums instead of file times to be more accurate
1522 rsync -ahvic --delete "$@"
1523 }
1524 rsa() {
1525 # like rlu, but dont delete files on the target end which
1526 # do not exist on the original end.
1527 rsync -ahvic "$@"
1528 }
1529 rst() {
1530 # rl without preserving modification time.
1531 rsync -ahvic --delete --no-t "$@"
1532 }
1533 rsu() { # [OPTS] HOST PATH
1534 # eg. rlu -opts frodo /testpath
1535 # relative paths will expanded with readlink -f.
1536 opts=("${@:1:$#-2}") # 1 to last -2
1537 path="${*:$#}" # last
1538 host="${*:$#-1:1}" # last -1
1539 if [[ $path == .* ]]; then
1540 path=$(readlink -f $path)
1541 fi
1542 # rync here uses checksum instead of time so we dont mess with
1543 # unison relying on time as much. g is for group, same reason
1544 # to keep up with unison.
1545 m s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1546 }
1547 ccomp rsync rsd rsa rst rsu
1548
1549 # find programs listening on a port
1550 ssp() {
1551 local port=$1
1552 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
1553 s ss -lpn state listening sport = $port
1554 }
1555
1556 resolvcat() {
1557 local f
1558 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1559 m s nscd -i hosts
1560 fi
1561 f=/etc/resolv.conf
1562 echo $f:; ccat $f
1563 hr; s ss -lpn sport = 53
1564 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1565 # this will fail is dnsmasq is failed
1566 hr; m ser status dnsmasq | cat || :
1567 f=/etc/dnsmasq.conf
1568 hr; echo $f:; ccat $f
1569 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1570 f=/etc/dnsmasq-servers.conf
1571 hr; echo $f:; ccat $f
1572 fi
1573 hr
1574 echo /etc/nsswitch.conf:
1575 grep '^ *hosts:' /etc/nsswitch.conf
1576 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1577 hr; m ser status systemd-resolved | cat || :
1578 hr; m resolvectl status | cat
1579 fi
1580
1581 }
1582 rcat() {
1583 resolvcat | less
1584 }
1585 reresolv() {
1586 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1587 m ser stop nscd
1588 sleep .5
1589 m ser start nscd
1590 m sudo nscd -i hosts
1591 fi
1592 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1593 m sudo systemctl restart dnsmasq
1594 fi
1595 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1596 m sudo systemctl restart systemd-resolved
1597 fi
1598 if type -P resolvectl &>/dev/null; then
1599 resolvectl flush-caches
1600 fi
1601 }
1602
1603 rmstrips() {
1604 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1605 }
1606
1607 sudo () {
1608 command sudo "$@" || return $?
1609 DID_SUDO=true
1610 }
1611 s() {
1612 # background
1613 # I use a function because otherwise we cant use in a script,
1614 # cant assign to variable.
1615 #
1616 # note: gksudo is recommended for X apps because it does not set the
1617 # home directory to the same, and thus apps writing to ~ fuck things up
1618 # with root owned files.
1619 #
1620 if [[ $EUID != 0 || $1 == -* ]]; then
1621 # shellcheck disable=SC2034
1622 SUDOD="$PWD" command sudo -i "$@"
1623 DID_SUDO=true
1624 else
1625 "$@"
1626 fi
1627 }
1628 sb() { # sudo bash -c
1629 # use sb instead of s is for sudo redirections,
1630 # eg. sb 'echo "ok fine" > /etc/file'
1631 # shellcheck disable=SC2034
1632 local SUDOD="$PWD"
1633 sudo -i bash -c "$@"
1634 }
1635 ccomp sudo s sb
1636
1637 safe_rename() { # warn and dont rename if file exists.
1638 # mv -n exists, but it\'s silent
1639 if [[ $# != 2 ]]; then
1640 echo safe_rename error: $# args, need 2 >2
1641 return 1
1642 fi
1643 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1644 if [[ -e $2 || -L $2 ]]; then
1645 echo "Cannot rename $1 to $2 as it already exists."
1646 else
1647 mv -vi "$1" "$2"
1648 fi
1649 fi
1650 }
1651
1652
1653 sd() {
1654 sudo dd status=none of="$1"
1655 }
1656
1657 ser() {
1658 if type -p systemctl &>/dev/null; then
1659 s systemctl "$@"
1660 else
1661 if (( $# >= 3 )); then
1662 echo iank: ser expected 2 or less arguments
1663 return 1
1664 fi
1665 s service $2 $1
1666 fi
1667 }
1668 serstat() {
1669 systemctl -n 40 status "$@"
1670 }
1671
1672 seru() { systemctl --user "$@"; }
1673 # like restart, but do nothing if its not already started
1674 srestart() {
1675 local service=$1
1676 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1677 systemctl restart $service
1678 fi
1679 }
1680
1681 setini() { # set a value in a .ini style file
1682 key="$1" value="$2" section="$3" file="$4"
1683 if [[ -s $file ]]; then
1684 sed -ri -f - "$file" <<EOF
1685 # remove existing keys
1686 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1687 # add key
1688 /^\s*\[$section\]/a $key=$value
1689 # from section to eof, do nothing
1690 /^\s*\[$section\]/,\$b
1691 # on the last line, if we haven't found section yet, add section and key
1692 \$a [$section]\\
1693 $key=$value
1694 EOF
1695 else
1696 cat >"$file" <<EOF
1697 [$section]
1698 $key=$value
1699 EOF
1700 fi
1701 }
1702
1703 sgo() { # service go
1704 service=$1
1705 ser restart $service || return 1
1706 if type -p systemctl &>/dev/null; then
1707 ser enable $service
1708 fi
1709 }
1710 soff () {
1711 for service; do
1712 # ignore services that dont exist
1713 if systemctl cat $service &>/dev/null; then
1714 ser stop $service;
1715 ser disable $service
1716 fi
1717 done
1718 }
1719
1720 sgu() {
1721 systemctl list-unit-files | rg "$@"
1722 }
1723
1724
1725 sk() {
1726
1727
1728 # disable a warning with:
1729 # shellcheck disable=SC2206 # reasoning
1730
1731 # see bash-template/style-guide.md for justifications
1732
1733 local quotes others
1734 quotes=2048,2068,2086,2206
1735 others=2029,2033,2164
1736 shellcheck -W 999 -x -e $quotes,$others "$@" || return $?
1737 }
1738
1739
1740 # sl: ssh, but firsh rsync our bashrc and related files to a special
1741 # directory on the remote host if needed.
1742
1743 # Some environment variables and files need to be setup for this to work
1744 # (mine are set at the beginning of this file)
1745
1746 # SL_FILES_DIR: Environment variable. Path to folder which should at
1747 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1748 # remote hosts (top level symlinks are resolved) unless the host already
1749 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1750 # control and sync files to separately and already has the ~/.bashrc you
1751 # want. The remote bash will also take its .inputrc config from this
1752 # folder (default of not existing is fine). Mine looks like this:
1753 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1754
1755 # SL_INFO_DIR: Environment variable. This folder stores info about what
1756 # we detected on the remote system and when we last synced. It will be created
1757 # if it does not exist. Sometimes you may want to forget about a
1758 # remote system, you can use sl --rsync, or the function for that slr
1759 # below.
1760
1761 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1762 # depending on the remote host. Run this string on the remote host the
1763 # first time sl is run (or if we run slr). The result is passed to
1764 # SL_TEST_HOOK. For example,
1765 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1766
1767 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1768 # $SL_FILES_DIR to vary the files synced.
1769
1770 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1771 # example to exclude files within a directory. Note, excluded
1772 # files wont be deleted on rsync, you can add --delete-excluded
1773 # to the rsync command if that is desired.
1774
1775 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1776
1777 # For when ~/.bashrc is already customized on the remote server, you
1778 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1779 # commands, even in scripts. This paragraph is all about that. bash
1780 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1781 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1782 # and if you customize it, probably has bugs from time to time. This is
1783 # bad. Here's how I fix it. I have a special condition to "return" in my
1784 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1785 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1786 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1787 # separate file because even if I return early on, the whole file gets
1788 # parsed which can fail if there is a syntax error.
1789 sl() {
1790 # Background on LC_USEBASHRC var (no need to read if you just want to
1791 # use this function): env variables sent across ssh are strictly
1792 # limited, but we get LC_* at least in debian based machines, so we
1793 # just make that * be something no normal program would use. Note, on
1794 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1795 # set, and the inner shell also allows running a nondefault
1796 # .bashrc. This means the outer shell still ran the default .bashrc,
1797 # but that is the best we can do.
1798
1799 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1800 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1801 declare -a args tmpa
1802
1803 args=($SL_SSH_ARGS)
1804
1805 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1806 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1807 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1808 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
1809 # [command]
1810
1811 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
1812 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
1813 # [-F configfile] [-I pkcs11] [-i identity_file]
1814 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
1815 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
1816 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
1817
1818 force_rsync=false
1819 if [[ $1 == --rsync ]]; then
1820 force_rsync=true
1821 shift
1822 fi
1823
1824 sl_test_cmd=$SL_TEST_CMD
1825 sl_test_hook=$SL_TEST_HOOK
1826 sl_rsync_args=$SL_RSYNC_ARGS
1827 while [[ $1 ]]; do
1828 case "$1" in
1829 --rsync)
1830 force_rsync=true
1831 ;;
1832 --sl-test-cmd)
1833 sl_test_cmd="$2"
1834 shift
1835 ;;
1836 --sl-test-hook)
1837 sl_test_hook="$2"
1838 shift
1839 ;;
1840 --sl-rsync-args)
1841 sl_rsync_args="$2"
1842 shift
1843 ;;
1844 *)
1845 break
1846 ;;
1847 esac
1848 shift
1849 done
1850
1851 while [[ $1 ]]; do
1852 case "$1" in
1853 # note we dont support things like -4oOption
1854 -[46AaCfGgKkMNnqsTtVvXxYy]*)
1855 args+=("$1"); shift
1856 ;;
1857 -[bcDEeFIiJLlmOopQRSWw]*)
1858 # -oOption etc is valid
1859 if (( ${#1} >= 3 )); then
1860 args+=("$1"); shift
1861 else
1862 args+=("$1" "$2"); shift 2
1863 fi
1864 ;;
1865 *)
1866 break
1867 ;;
1868 esac
1869 done
1870 remote="$1"
1871 if [[ ! $remote ]]; then
1872 echo $0: error hostname required >&2
1873 return 1
1874 fi
1875 shift
1876
1877 if [[ ! $SL_INFO_DIR ]]; then
1878 echo error: missing '$SL_INFO_DIR' env var >&2
1879 return 1
1880 fi
1881
1882 dorsync=false
1883 haveinfo=false
1884 tmpa=($SL_INFO_DIR/???????????"$remote")
1885 sshinfo=${tmpa[0]}
1886 if [[ -e $sshinfo ]]; then
1887 if $force_rsync; then
1888 rm -f $sshinfo
1889 else
1890 haveinfo=true
1891 fi
1892 fi
1893 if $haveinfo; then
1894 tmp=${sshinfo[0]##*/}
1895 tmp2=${tmp::11}
1896 type=${tmp2: -1}
1897 extra_info=$(cat $sshinfo)
1898 else
1899 # we test for string to know ssh succeeded
1900 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
1901 testcmd="if $testbool; then printf y; else printf n; fi"
1902 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
1903 echo failed sl test. doing plain ssh -v
1904 command ssh -v "${args[@]}" "$remote"
1905 fi
1906 if [[ $tmp == y* ]]; then
1907 type=a
1908 else
1909 dorsync=true
1910 type=b
1911 fi
1912 extra_info="${tmp:1}"
1913 fi
1914 if [[ $sl_test_hook ]]; then
1915 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
1916 fi
1917
1918 if $haveinfo && [[ $type == b ]]; then
1919 info_sec=${tmp::10}
1920 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
1921 files_sec=${files_sec%%.*}
1922 if (( files_sec > info_sec )); then
1923 dorsync=true
1924 rm -f $sshinfo
1925 fi
1926 fi
1927
1928 sync_dirname=${SL_FILES_DIR##*/}
1929
1930 if [[ ! $SL_FILES_DIR ]]; then
1931 echo error: missing '$SL_FILES_DIR' env var >&2
1932 return 1
1933 fi
1934
1935 if $dorsync; then
1936 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
1937 fi
1938 if $dorsync || ! $haveinfo; then
1939 sshinfo=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
1940 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
1941 printf "%s\n" "$extra_info" >$sshinfo
1942 chmod 666 $sshinfo
1943 fi
1944 if [[ $type == b ]]; then
1945 if (( ${#@} )); then
1946 # Theres a couple ways to pass arguments, im not sure whats best,
1947 # but relying on bash 4.4+ escape quoting seems most reliable.
1948 command ssh "${args[@]}" "$remote" \
1949 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
1950 elif [[ ! -t 0 ]]; then
1951 # This case is when commands are being piped to ssh.
1952 # Normally, no bashrc gets sourced.
1953 # But, since we are doing all this, lets source it because we can.
1954 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1955 else
1956 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
1957 fi
1958 else
1959 if [[ -t 0 ]]; then
1960 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
1961 else
1962 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1963 fi
1964 fi
1965 # this function inspired from https://github.com/Russell91/sshrc
1966 }
1967
1968 slr() {
1969 sl --rsync "$@"
1970 }
1971 sss() { # ssh solo
1972 sl -oControlMaster=no -oControlPath=/ "$@"
1973 }
1974 # kill off old shared socket then ssh
1975 ssk() {
1976 m ssh -O exit "$@" || [[ $? == 255 ]]
1977 m sl "$@"
1978 }
1979 ccomp ssh sl slr sss ssk
1980 # plain ssh
1981 ssh() {
1982 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
1983 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
1984 else
1985 LC_USEBASHRC=t command ssh "$@"
1986 fi
1987 }
1988
1989
1990 slog() {
1991 # log with script. timing is $1.t and script is $1.s
1992 # -l to save to ~/typescripts/
1993 # -t to add a timestamp to the filenames
1994 local logdir do_stamp arg_base
1995 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1996 logdir="/a/dt/"
1997 do_stamp=false
1998 while getopts "lt" option
1999 do
2000 case $option in
2001 l ) arg_base=$logdir ;;
2002 t ) do_stamp=true ;;
2003 esac
2004 done
2005 shift $((OPTIND - 1))
2006 arg_base+=$1
2007 [[ -e $logdir ]] || mkdir -p $logdir
2008 $do_stamp && arg_base+=$(date +%F.%T%z)
2009 script -t $arg_base.s 2> $arg_base.t
2010 }
2011 splay() { # script replay
2012 #logRoot="$HOME/typescripts/"
2013 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2014 scriptreplay "$1.t" "$1.s"
2015 }
2016
2017 sr() {
2018 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2019 if [[ $# == 0 ]]; then
2020 sudo -E bash -c -l "$(history -p '!!')"
2021 else
2022 echo this command redos last history item. no argument is accepted
2023 fi
2024 }
2025
2026 srm () {
2027 # with -ll, less secure but faster.
2028 command srm -ll "$@"
2029 }
2030
2031 srun() {
2032 scp $2 $1:/tmp
2033 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
2034 }
2035
2036
2037 swap() {
2038 local tmp
2039 tmp=$(mktemp)
2040 mv $1 $tmp
2041 mv $2 $1
2042 mv $tmp $2
2043 }
2044
2045 tclock() { # terminal clock
2046 local x
2047 clear
2048 date +%l:%_M
2049 len=60
2050 # this goes to full width
2051 #len=${1:-$((COLUMNS -7))}
2052 x=1
2053 while true; do
2054 if (( x == len )); then
2055 end=true
2056 d="$(date +%l:%_M) "
2057 else
2058 end=false
2059 d=$(date +%l:%M:%_S)
2060 fi
2061 echo -en "\r"
2062 echo -n "$d"
2063 for ((i=0; i<x; i++)); do
2064 if (( i % 6 )); then
2065 echo -n _
2066 else
2067 echo -n .
2068 fi
2069 done
2070 if $end; then
2071 echo
2072 x=1
2073 else
2074 x=$((x+1))
2075 fi
2076 sleep 5
2077 done
2078 }
2079
2080
2081 te() {
2082 # test existence / exists
2083 local ret=0
2084 for x in "$@"; do
2085 [[ -e "$x" || -L "$x" ]] || ret=1
2086 done
2087 return $ret
2088 }
2089
2090 psoff() {
2091 # normally, i would just execute these commands in the function.
2092 # however, DEBUG is not inherited, so we need to run it outside a function.
2093 # And we want to run set -x afterwards to avoid spam, so we cram everything
2094 # in here, and then it will run after this function is done.
2095 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
2096 }
2097 pson() {
2098 PROMPT_COMMAND=prompt-command
2099 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2100 trap 'settitle "$BASH_COMMAND"' DEBUG
2101 fi
2102 }
2103
2104 tx() { # toggle set -x, and the prompt so it doesnt spam
2105 if [[ $- == *x* ]]; then
2106 set +x
2107 pson
2108 else
2109 psoff
2110 fi
2111 }
2112
2113 psnetns() {
2114 # show all processes in the network namespace $1.
2115 # blank entries appear to be subprocesses/threads
2116 local x netns
2117 netns=$1
2118 ps -w | head -n 1
2119 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
2120 while read -r l; do
2121 x=$(ps -w --no-headers -p $l);
2122 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2123 done
2124 }
2125 nonet() {
2126 if ! s ip netns list | grep -Fx nonet &>/dev/null; then
2127 s ip netns add nonet
2128 fi
2129 sudo -E env /sbin/ip netns exec nonet sudo -E -u iank /bin/bash
2130 }
2131
2132 m() { printf "%s\n" "$*"; "$@"; }
2133
2134 uptime() {
2135 if type -p uprecords &>/dev/null; then
2136 uprecords -B
2137 else
2138 command uptime
2139 fi
2140 }
2141
2142 virshrm() {
2143 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
2144 }
2145
2146 vm-set-listen(){
2147 local t
2148 t=$(mktemp)
2149 local vm=$1
2150 local ip=$2
2151 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2152 sed -r "s/listen='[^']+/listen='$ip/"> $t
2153 sudo virsh undefine $vm
2154 sudo virsh define $t
2155 }
2156
2157
2158 vmshare() {
2159 vm-set-listen $1 0.0.0.0
2160 }
2161
2162
2163 vmunshare() {
2164 vm-set-listen $1 127.0.0.1
2165 }
2166
2167 myiwscan() {
2168 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2169 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2170 sudo iw dev wls1 scan | sed -rn "
2171 s/^\Wcapability: (.*)/\1/;Ta;h;b
2172 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2173 # padded to min width of 20
2174 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2175 "|sort -r
2176 }
2177
2178 # * misc stuff
2179
2180
2181 if $use_color && type -p tput &>/dev/null; then
2182 term_bold="$(tput bold)"
2183 term_red="$(tput setaf 1)"
2184 term_green="$(tput setaf 2)"
2185 term_yellow="$(tput setaf 3)"
2186 term_purple="$(tput setaf 5)"
2187 term_nocolor="$(tput sgr0)" # no font attributes
2188
2189 # unused so far. commented for shellcheck
2190 # term_underl="$(tput smul)"
2191 # term_blue="$(tput setaf 4)"
2192 # term_cyan="$(tput setaf 6)"
2193 fi
2194 # Try to keep environment pollution down, EPA loves us.
2195 unset safe_term match_lhs use_color
2196
2197 # * prompt
2198
2199
2200 if [[ $- == *i* ]]; then
2201
2202
2203 case $HOSTNAME in
2204 bk|je|li)
2205 if [[ $EUID == 1000 ]]; then
2206 system-status _ ||:
2207 fi
2208 ;;
2209 esac
2210
2211
2212 # this needs to come before next ps1 stuff
2213 # this stuff needs bash 4, feb 2009,
2214 # old enough to no longer condition on $BASH_VERSION anymore
2215 shopt -s autocd
2216 shopt -s dirspell
2217 PS1='\w'
2218 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2219 PROMPT_DIRTRIM=2
2220 bind -m vi-command B:shell-backward-word
2221 bind -m vi-command W:shell-forward-word
2222 fi
2223
2224 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2225 unset PROMPT_DIRTRIM
2226 PS1="\h:$PS1"
2227 fi
2228
2229 # emacs terminal has problems if this runs slowly,
2230 # so I've thrown a bunch of things at the wall to speed it up.
2231 prompt-command() {
2232 local return=$? # this MUST COME FIRST
2233 local ps_char ps_color
2234 unset IFS
2235
2236 if [[ $HISTFILE ]]; then
2237 history -a # save history
2238 fi
2239
2240 # assigned in brc2
2241 # shellcheck disable=SC1303
2242 if [[ $jr_pid ]]; then
2243 if [[ -e /proc/$jr_pid ]]; then
2244 kill $jr_pid
2245 fi
2246 unset jr_pid
2247 fi
2248
2249 case $return in
2250 0) ps_color="$term_purple"
2251 ps_char='\$'
2252 ;;
2253 *) ps_color="$term_green"
2254 ps_char="$return \\$"
2255 ;;
2256 esac
2257 if [[ ! -O . ]]; then # not owner
2258 if [[ -w . ]]; then # writable
2259 ps_color="$term_bold$term_red"
2260 else
2261 ps_color="$term_bold$term_green"
2262 fi
2263 fi
2264
2265 # faster than sourceing the file im guessing
2266 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2267 eval $(< /dev/shm/iank-status)
2268 fi
2269 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2270 ps_char="@ $ps_char"
2271 fi
2272 # We could test if sudo is active with sudo -nv
2273 # but then we get an email and log of lots of failed sudo commands.
2274 # We could turn those off, but seems better not to.
2275 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2276 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2277 fi
2278 if [[ ! $HISTFILE ]]; then
2279 ps_char="NOHIST $ps_char"
2280 fi
2281 PS1="${PS1%"${PS1#*[wW]}"} $psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2282
2283 # set titlebar. instead, using more advanced
2284 # titelbar below
2285 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2286 }
2287 PROMPT_COMMAND=prompt-command
2288
2289 if [[ $TERM == screen* ]]; then
2290 _title_escape="\033]..2;"
2291 else
2292 # somme sites recommend this, i dunno what the diff is.
2293 #_title_escape="\033]30;"
2294 _title_escape="\033]0;"
2295 fi
2296
2297 settitle () {
2298 # this makes it so we show the current command if
2299 # one is running, otherwise, show nothing
2300
2301 if [[ $1 == prompt-command ]]; then
2302 return 0
2303 fi
2304 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
2305 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2306 printf "%s" "$*"
2307 echo -ne "\007"
2308 fi
2309 }
2310
2311 # note, this wont work:
2312 # x=$(mktemp); cp a $x
2313 # I havnt figured out why, bigger fish to fry.
2314 #
2315 # for titlebar.
2316 # condition from the screen man page i think.
2317 # note: duplicated in tx()
2318 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2319 trap 'settitle "$BASH_COMMAND"' DEBUG
2320 else
2321 trap DEBUG
2322 fi
2323
2324 fi
2325
2326 # * stuff that makes sense to be at the end
2327
2328
2329 # best practice
2330 unset IFS
2331
2332 # shellcheck disable=SC1090
2333 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2334
2335 # I had this idea to start a bash shell which would run an initial
2336 # command passed through this env variable, then continue on
2337 # interactively. But the use case I had in mind went away.
2338 #
2339 # if [[ $MY_INIT_CMD ]]; then
2340 # "${MY_INIT_CMD[@]}"
2341 # unset MY_INIT_CMD
2342 # fi
2343
2344 # ensure no bad programs appending to this file will have an affect
2345 return 0