lots of fixes, automation for bitfolk
[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 # [[ -d /home/iank/.iank/e/e ]] mounts it unnecessarily, so use this.
242 if grep -qF /home/iank/.iank/e/e /etc/auto.iank /etc/exports &>/dev/null; then
243 export EMACSDIR=/home/iank/.iank/e/e
244 fi
245 path-add $bashrc_dir
246 fi
247 fi
248
249 # if someone exported $SOE (stop on error), catch errors.
250 #
251 # Note, on debian this results in the following warning when in ssh,
252 # hich I haven't figured out how to fix. It doesn't happen if we source
253 # after the shell has started
254 #
255 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
256 # bash: warning: cannot start debugger; debugging mode disabled
257 if [[ $SOE ]]; then
258 if [[ -e /a/bin/errhandle/err ]]; then
259 source /a/bin/errhandle/err
260 fi
261 fi
262
263 # based on readme.debian. dunno if this will break on other distros.
264 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
265 source /usr/share/wcd/wcd-include.sh
266 fi
267
268
269 mysrc() {
270 local path dir file
271 path=$1
272 dir=${path%/*}
273 file=${path##*/}
274 if [[ -s $path ]]; then
275 source $path
276 elif [[ -s $bashrc_dir/$file ]]; then
277 source $bashrc_dir/$file
278 fi
279 }
280
281
282 mysrc /a/bin/small-misc-bash/ll-function
283 mysrc /a/bin/distro-functions/src/package-manager-abstractions
284
285
286 # * functions
287 ccomp() { # copy completion
288 local src=$1
289 local c
290 shift
291 if ! c=$(complete -p $src 2>/dev/null); then
292 _completion_loader $src &>/dev/null ||:
293 c=$(complete -p $src 2>/dev/null) || return 0
294 fi
295 # remove $src( .*|$)
296 c=${c% $src}
297 c=${c%% $src *}
298 eval $c $*
299 }
300
301
302 ..() { c ..; }
303 ...() { c ../..; }
304 ....() { c ../../..; }
305 .....() { c ../../../..; }
306 ......() { c ../../../../..; }
307
308 chere() {
309 local f path
310 for f; do
311 path=$(readlink -e "$f")
312 echo "cat >$path <<'EOF'"
313 cat "$f"
314 echo EOF
315 done
316 }
317
318
319 # file cut copy and paste, like the text buffers :)
320 # I havnt tested these.
321 _fbufferinit() { # internal use
322 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
323 rm -rf "${my_f_tempdir:?}"/*
324 }
325 fcp() { # file cp
326 _fbufferinit
327 cp "$@" "$my_f_tempdir"/
328 }
329 fct() { # file cut
330 _fbufferinit
331 mv "$@" "$my_f_tempdir"/
332 }
333 fpst() { # file paste
334 [[ $2 ]] && { echo too many arguments; return 1; }
335 target=${1:-.}
336 cp "$my_f_tempdir"/* "$target"
337 }
338
339 _khfix_common() {
340 local host ip port file key
341 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" ||: )
342 file=$(readlink -f ~/.ssh/known_hosts)
343 if [[ ! $ip ]]; then
344 echo "khfix: ssh failed"
345 return 1
346 fi
347 if [[ $port != 22 ]]; then
348 ip_entry="[$ip]:$port"
349 host_entry="[$host]:$port"
350 else
351 ip_entry=$ip
352 host_entry=$host
353 fi
354 tmpfile=$(mktemp)
355 if [[ $host != $ip ]]; then
356 key=$(ssh-keygen -F "$host_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
357 if [[ $key ]]; then
358 grep -Fv "$key" "$file" | sponge "$file"
359 fi
360 fi
361 key=$(ssh-keygen -F "$ip_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
362 if [[ $key ]]; then
363 grep -Fv "$key" "$file" | sponge "$file"
364 fi
365 ll ~/.ssh/known_hosts
366 rootsshsync
367 }
368 khfix() { # known hosts fix
369 _khfix_common "$@" || return 1
370 ssh $1 :
371 }
372 khcopy() {
373 _khfix_common "$@"
374 ssh-copy-id $1
375 }
376
377 a() {
378 local x
379 x=$(readlink -nf "${1:-$PWD}")
380 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
381 echo -n "$x" | xclip -selection clipboard
382 echo -n "$x" | xclip
383 }
384
385 # a1 = awk {print $1}
386 for field in {1..20}; do
387 eval a$field"() { awk '{print \$$field}'; }"
388 done
389 # h1 = head -n1
390 for num in {1..9}; do
391 eval h$num"() { head -n$num; }"
392 done
393
394
395 b() {
396 # backwards
397 c -
398 }
399
400 vp9() {
401 in=$PWD/$1
402
403 if [[ $2 ]]; then
404 out=$PWD/$2
405 else
406 out=$PWD/vp9/$1
407 fi
408 cd $(mktemp -d)
409 pwd
410 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 && \
411 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
412 cd -
413 }
414
415 utcl() { # utc 24 hour time to local hour 24 hour time
416 echo "print( ($1 $(date +%z | sed -r 's/..$//;s/^(-?)0*/\1/')) % 24)"|python3
417 }
418
419 # c. better cd
420 if type -p wcd &>/dev/null; then
421 if [[ $LC_INSIDE_EMACS ]]; then
422 c() { wcd -c -z 50 -o "$@"; }
423 else
424 # lets see what the fancy terminal does from time to time
425 c() { wcd -c -z 50 "$@"; }
426 fi
427 else
428 c() { cd "$@"; }
429 fi
430 ccomp cd c
431
432 c4() { c /var/log/exim4; }
433
434 caa() { git commit --amend --no-edit -a; }
435
436 cf() {
437 for f; do
438 hr
439 echo "$f"
440 hr
441 cat "$f"
442 done
443 }
444 caf() {
445 # shellcheck disable=SC2033
446 find -L "$@" -type f -not \( -name .svn -prune -o -name .git -prune \
447 -o -name .hg -prune -o -name .editor-backups -prune \
448 -o -name .undo-tree-history -prune \) \
449 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
450
451 }
452 ccomp cat cf caf
453
454 calc() { echo "scale=3; $*" | bc -l; }
455 # no having to type quotes, but also no command history:
456 clc() {
457 local x
458 read -r x
459 echo "scale=3; $x" | bc -l
460 }
461
462 cam() {
463 git commit -am "$*"
464 }
465
466 ccat () { # config cat. see a config without extra lines.
467 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
468 }
469 ccomp grep ccat
470
471 chrbind() {
472 local d
473 # dev/pts needed for pacman signature check
474 for d in dev proc sys dev/pts; do
475 [[ -d $d ]]
476 if ! mountpoint $d &>/dev/null; then
477 s mount -o bind /$d $d
478 fi
479 done
480 }
481
482
483 _cdiff-prep() {
484 # join options which are continued to multiples lines onto one line
485 local first=true
486 while IFS= read -r line; do
487 # remove leading spaces/tabs. assumes extglob
488 if [[ $line == "[ ]*" ]]; then
489 line="${line##+( )}"
490 fi
491 if $first; then
492 pastline="$line"
493 first=false
494 elif [[ $line == *=* ]]; then
495 echo "$pastline" >> "$2"
496 pastline="$line"
497 else
498 pastline="$pastline $line"
499 fi
500 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
501 echo "$pastline" >> "$2"
502 }
503
504 cdiff() {
505 # diff config files,
506 # setup for format of postfix, eg:
507 # option = stuff[,]
508 # [more stuff]
509 local pastline unified f1 f2
510 unified="$(mktemp)"
511 f1="$(mktemp)"
512 f2="$(mktemp)"
513 _cdiff-prep "$1" "$f1"
514 _cdiff-prep "$2" "$f2"
515 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
516 while IFS= read -r line; do
517 # the default bright red / blue doesnt work in emacs shell
518 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
519 done < "$unified"
520 }
521
522
523 cat-new-files() {
524 local start=$SECONDS
525 local dir="$1"
526 inotifywait -m "$dir" -e create -e moved_to |
527 # shellcheck disable=SC2030
528 while read -r filedir _ file; do
529 cat "$filedir$file"
530 hr
531 calc $((SECONDS - start)) / 60
532 sleep 5
533 done
534
535 }
536
537 # shellcheck disable=SC2032
538 chown() {
539 # makes it so chown -R symlink affects the symlink and its target.
540 if [[ $1 == -R ]]; then
541 shift
542 command chown -h "$@"
543 command chown -R "$@"
544 else
545 command chown "$@"
546 fi
547 }
548
549 cim() {
550 git commit -m "$*"
551 }
552
553 cl() {
554 # choose recent directory. cl = cd list
555 c =
556 }
557
558 d() { builtin bg "$@"; }
559 ccomp bg d
560
561 dc() {
562 diff --strip-trailing-cr -w "$@" # diff content
563 }
564 ccomp diff dc
565
566 despace() {
567 local x y
568 for x in "$@"; do
569 y="${x// /_}"
570 safe_rename "$x" "$y"
571 done
572 }
573
574 dig() {
575 command dig +nostats +nocmd "$@"
576 }
577 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
578 digsort() {
579 local sec
580 sec=
581 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
582 if [[ $l == [^\;]* ]]; then
583 sec+="$l"$'\n'
584 else
585 if [[ $sec ]]; then
586 printf "%s" "$sec" | sort
587 sec=
588 fi
589 printf "%s\n" "$l"
590 fi
591 done
592 }
593 ccomp dig digsort
594 # compare digs to the 2 servers
595 # usage: digdiff @server1 @server2 DIG_ARGS
596 # note: only the soa master nameserver will respond with
597 # ra "recursive answer" flag. That difference is meaningless afaik.
598 digdiff() {
599 local s1 s2
600 s1=$1
601 shift
602 s2=$1
603 shift
604 digsort $s1 "$@" | tee /tmp/digdiff
605 diff -u /tmp/digdiff <(digsort $s2 "$@")
606 }
607
608 dt() {
609 date "+%A, %B %d, %r" "$@"
610 }
611 ccomp date dt
612
613 dus() { # du, sorted, default arg of
614 du -sh ${@:-*} | sort -h
615 }
616 ccomp du dus
617
618
619 e() { echo "$@"; }
620
621 # echo args
622 ea() {
623 if (( ! $# )); then
624 echo no args
625 fi
626 for arg; do
627 printf "%qEOL\n" "${arg}"
628 printf "%s" "${arg}" |& hexdump -C
629 done
630 }
631 # echo vars. print var including escapes, etc
632 ev() {
633 if (( ! $# )); then
634 echo no args
635 fi
636 for arg; do
637 if [[ -v $arg ]]; then
638 printf "%qEOL\n" "${!arg}"
639 printf "%s" "${!arg}" |& hexdump -C
640 else
641 echo arg $arg is unset
642 fi
643 done
644 }
645
646 ediff() {
647 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
648 emacs --eval "(ediff-files \"$1\" \"$2\")"
649 }
650
651 # mail related
652 etail() {
653 tail -F /var/log/exim4/mainlog -n 200 "$@"
654 }
655 ccomp tail etail
656
657 # print exim old pids
658 eoldpids() {
659 local configtime pid piduptime now daemonpid
660 printf -v now '%(%s)T' -1
661 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
662 if [[ -s /run/exim4/exim.pid ]]; then
663 daemonpid=$(cat /run/exim4/exim.pid)
664 fi
665 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
666 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
667 if [[ $pid == $daemonpid ]]; then
668 continue
669 fi
670 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
671 if (( configtime > now - piduptime )); then
672 echo $pid
673 fi
674 done
675 }
676
677 # exim tail but only watch lines from new pids
678 etailnew() {
679 local pid oldpids
680 for pid in $(eoldpids); do
681 oldpids+="$pid|"
682 done
683 if [[ $oldpids ]]; then
684 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
685 else
686 etail
687 fi
688 }
689 # exim watch as old pids go away
690 ewatchold() {
691 local configtime pid piduptime now
692 local -i count
693 local -a oldpids
694 count=0
695 while true; do
696 oldpids=($(eoldpids))
697 if (( ! ${#oldpids[@]} )); then
698 return
699 fi
700 # print the date every 20 iterations
701 if (( ! count % 20 )); then
702 date
703 fi
704 count+=1
705 ps -f -p "${oldpids[*]}"
706 sleep 1
707 done
708 }
709
710 eless() {
711 less /var/log/exim4/mainlog
712 }
713 ccomp less eless
714 eqcat() {
715 exiqgrep -i -o 60 | while read -r i; do
716 hlm exim -Mvc $i
717 echo
718 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
719 done
720 }
721 eqrmf() {
722 exiqgrep -i | xargs exim -Mrm
723 }
724
725 econfdevnew() {
726 rm -rf /tmp/edev
727 mkdir -p /tmp/edev/etc
728 cp -ra /etc/exim4 /tmp/edev/etc
729 cp -ra /etc/alias* /tmp/edev/etc
730 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
731 econfdev
732 }
733 econfdev() {
734 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
735 }
736
737
738
739 # shellcheck disable=SC2032
740 f() {
741 # cd forward
742 c +
743 }
744
745 fa() {
746 # find array. make an array of file names found by find into $x
747 # argument: find arguments
748 # return: find results in an array $x
749 while read -rd ''; do
750 x+=("$REPLY");
751 done < <(find "$@" -print0);
752 }
753
754 faf() { # find all files. use -L to follow symlinks
755 find "$@" -not \( -name .svn -prune -o -name .git -prune \
756 -o -name .hg -prune -o -name .editor-backups -prune \
757 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
758 }
759
760 # todo: id like to do maybe a daily or hourly cronjob to
761 # check that my history file size is increasing. Ive had it
762 # inexplicably truncated in the past.
763 histrm() {
764 history -n
765 history | awk -v IGNORECASE=1 '{ a=$1; sub(/^( *[^ ]+){4} */, "") }; /'"$*"'/'
766 read -p "press anything but contrl-c to delete"
767 for entry in $(history | awk -v IGNORECASE=1 '{ a=$1; sub(/^( *[^ ]+){4} */, "") }; /'"$*"'/ { print a }' | tac); do
768 history -d $entry
769 done
770 history -w
771 }
772
773 # mail related
774 frozen() {
775 rm -rf /tmp/frozen
776 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
777 sudo exim -Mvl $id
778 echo
779 sudo exim -Mvh $id
780 echo
781 sudo exim -Mvb $id
782 echo -e '\n\n##############################\n'
783 done | tee -a /tmp/frozen
784 }
785 frozenrm() {
786 local ids=()
787 while read -r line; do
788 printf '%s\n' "$line"
789 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
790 done < <(s mailq)
791 echo "sleeping for 2 in case you change your mind"
792 sleep 2
793 sudo exim -Mrm "${ids[@]}"
794 }
795
796 funce() {
797 # like -e for functions. returns on error.
798 # at the end of the function, disable with:
799 # trap ERR
800 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
801 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
802 trap ERR
803 return' ERR
804 }
805
806 getdir () {
807 local help="Usage: getdir [--help] PATH
808 Output the directory of PATH, or just PATH if it is a directory."
809 if [[ $1 == --help ]]; then
810 echo "$help"
811 return 0
812 fi
813 if [[ $# -ne 1 ]]; then
814 echo "getdir error: expected 1 argument, got $#"
815 return 1
816 fi
817 if [[ -d $1 ]]; then
818 echo "$1"
819 else
820 local dir
821 dir="$(dirname "$1")"
822 if [[ -d $dir ]]; then
823 echo "$dir"
824 else
825 echo "getdir error: directory does not exist"
826 return 1
827 fi
828 fi
829 }
830
831 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
832 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
833 local root
834 root=$(gitroot) || return 1 # function to set gitroot
835 builtin cd "$root"
836 git symbolic-ref HEAD refs/heads/$1
837 rm .git/index
838 git clean -fdx
839 }
840
841 # shellcheck disable=SC2120
842 gitroot() {
843 local help="Usage: gitroot [--help]
844 Print the full path to the root of the current git repo
845
846 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
847 and works in older versions of git which did not have that."
848 if [[ $1 == --help ]]; then
849 echo "$help"
850 return
851 fi
852 local p
853 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
854 [[ $p != /* ]] && p=$PWD
855 echo "${p%%/.git}"
856 }
857
858 g() {
859
860 # todo: patch emacs so it will look elsewhere. this is kinda sad:
861 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
862
863 local args gdb=false
864
865 if [[ $EMACSDIR ]]; then
866 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
867 fi
868
869 if [[ $DISPLAY ]]; then
870 args=-n
871 fi
872
873 if (( $# == 0 )); then
874 args+=" -c"
875 fi
876 # duplicate -c, but oh well
877 if ! pgrep -u $EUID emacsclient; then
878 if (( $# == 0 )) && type -p gdb &>/dev/null; then
879 gdb=true
880 else
881 args+=" -c"
882 fi
883 fi
884 if [[ $EMACSDIR ]]; then
885 # Alter the path here, otherwise the nfs mount gets triggered on the
886 # first path lookup when emacs is not being used.
887 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
888 else
889 if $gdb; then
890 # due to a bug, we cant debug from the start unless we get a new gdb
891 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
892 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
893 m emacsclient -a "" $args "$@"
894 sleep 1
895 cd /a/opt/emacs-$(distro-name)$(distro-num)
896 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
897 cd -
898 else
899 m emacsclient -a "" $args "$@"
900 fi
901 fi
902 }
903
904 # force terminal version
905 gn() {
906 g -n "$@"
907 }
908
909 gmacs() {
910 # quit will prompt if the program crashes.
911 gdb -ex=r -ex=quit --args emacs "$@"; r;
912 }
913
914 gdkill() {
915 # kill the emacs daemon
916 pk1 emacs --daemon
917 }
918
919 gr() {
920 grep -iIP --color=auto "$@" || return $?
921 }
922 grr() { # grep recursive
923 # Don't return 1 on nonmatch because this is meant to be
924 # interactive, not in a conditional.
925 if [[ ${#@} == 1 ]]; then
926 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
927 else
928 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
929 fi
930 }
931 ccomp grep gr grr
932
933 rg() { grr "$@"; }
934 ccomp grep rg
935
936 hr() { # horizontal row. used to break up output
937 printf "$(tput setaf 5 2>/dev/null ||:)â–ˆ$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
938 echo
939 }
940 # highlight
941 hl() {
942 local col input_len=0
943 for arg; do
944 input_len=$((input_len + 1 + ${#arg}))
945 done
946 col=$((60 - input_len))
947 printf "\e[1;97;41m%s" "$*"
948 if (( col > 0 )); then
949 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
950 fi
951 echo
952 }
953 hlm() { hl "$*"; "$@"; }
954
955 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
956
957
958 # get latest hub and run it
959 # main command to use:
960 # hub pull-request --no-edit
961 # --no-edit means to use the first commit\'s message as the pull request message.
962 # If that fails, try doing
963 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
964 # where branch is usually master. it does the pr against your current branch.
965 #
966 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
967 # it\'s at ~/.config/hub
968 hub() {
969 local up uptar updir p
970 p=/github/hub/releases/
971 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
972 uptar=${up##*/}
973 updir=${uptar%.tgz}
974 if [[ ! -e /a/opt/$updir ]]; then
975 rm -rf /a/opt/hub-linux-amd64*
976 wget -P /a/opt $up
977 tar -C /a/opt -zxf /a/opt/$uptar
978 rm -f /a/opt/$uptar
979 fi
980 if ! which hub &>/dev/null; then
981 sudo /a/opt/$updir/install
982 fi
983
984 # save token across computers
985 if [[ ! -L ~/.config/hub ]]; then
986 if [[ -e ~/.config/hub ]]; then
987 mv ~/.config/hub /p/c/subdir_files/.config/
988 fi
989 if [[ -e /p/c/subdir_files/.config/hub ]]; then
990 conflink
991 fi
992 fi
993 command hub "$@"
994 }
995
996 i() { git "$@"; }
997 ccomp git i
998
999 ic() {
1000 # fast commit all
1001 git commit -am "$*"
1002 }
1003
1004
1005 ifn() {
1006 # insensitive find
1007 find -L . -not \( -name .svn -prune -o -name .git -prune \
1008 -o -name .hg -prune -o -name .editor-backups -prune \
1009 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1010 }
1011
1012 ifd() {
1013 # insensitive find directory
1014 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
1015 -o -name .hg -prune -o -name .editor-backups -prune \
1016 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1017 }
1018
1019
1020 ipdrop() {
1021 sudo iptables -A INPUT -s $1 -j DROP
1022 }
1023
1024
1025 istext() {
1026 grep -Il "" "$@" &>/dev/null
1027 }
1028
1029 jtail() {
1030 journalctl -n 10000 -f "$@"
1031 }
1032 jr() { journalctl "$@" ; }
1033 jrf() { journalctl -f "$@" ; }
1034 jru() {
1035 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
1036 }
1037
1038 l() {
1039 if [[ $PWD == /[iap] ]]; then
1040 command ls -A --color=auto -I lost+found "$@"
1041 else
1042 command ls -A --color=auto "$@"
1043 fi
1044 }
1045
1046 lcn() { locate -i "*$**"; }
1047
1048 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
1049
1050 lt() { ll -tr "$@"; }
1051
1052 lld() { ll -d "$@"; }
1053
1054 ccomp ls l lg lt lld ll
1055
1056 # low recursively
1057 lowr() {
1058 local f dirs i a
1059 local -a all
1060 for dirs in false true; do
1061 for f; do
1062 if [[ -d $f ]]; then
1063 all=("$f"/**)
1064 # reverse the order to rename the nested dirs first.
1065 # note: 0 element is the dir itself
1066 for ((i=${#all[@]}-1; i>=1; i--)); do
1067 a="${all[i]}"
1068 if $dirs && [[ -d $a ]]; then
1069 # e dirs low "$a" # debug
1070 low "$a"
1071 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1072 # debug
1073 # e not dirs low "$a" # debug
1074 low "$a"
1075 fi
1076 done
1077 fi
1078 # just rename all the top level args on the second pass
1079 if $dirs; then
1080 # e final dirs low "$f" # debug
1081 low "$f"
1082 fi
1083 done
1084 done
1085 }
1086
1087 low() { # make filenames lowercase, remove bad chars
1088 local arg new dir f
1089 for arg; do
1090 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1091 dir="${arg%/*}"
1092 if (( ${#dir} == ${#arg} )); then
1093 dir=.
1094 fi
1095 f="${arg##*/}"
1096 new="${f,,}" # downcase
1097 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
1098 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1099 new="${new%"${new##*[[:alnum:]]}"}"
1100 # remove bad underscores, like __ and _._
1101 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1102 safe_rename "$dir/$f" "$dir/$new" || return 1
1103 done
1104 return 0
1105 }
1106
1107 lower() { # make first letter of filenames lowercase.
1108 local x
1109 for x in "$@"; do
1110 if [[ ${x::1} == [A-Z] ]]; then
1111 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1112 safe_rename "$x" "$y" || return 1
1113 fi
1114 done
1115 }
1116
1117
1118 k() { # history search
1119 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1120 }
1121 ks() { # history search
1122 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1123 }
1124 ccomp grep k ks
1125
1126
1127 make-targets() {
1128 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1129 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1130 }
1131
1132 mkc() {
1133 mkdir "$1"
1134 c "$1"
1135 }
1136 ccomp mkdir mkc
1137
1138 mkct() {
1139 mkc $(mktemp -d)
1140 }
1141
1142 mkt() { # mkdir and touch file
1143 local path="$1"
1144 mkdir -p "$(dirname "$path")"
1145 touch "$path"
1146 }
1147
1148 # shellcheck disable=SC2032
1149 mkdir() { command mkdir -p "$@"; }
1150
1151 nags() {
1152 # https://github.com/HenriWahl/Nagstamon/issues/357
1153 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1154 /usr/lib/notification-daemon/notification-daemon &
1155 fi
1156 /usr/bin/nagstamon &
1157 }
1158
1159 nmt() {
1160 s nmtui-connect "$@"
1161 }
1162
1163 nopanic() {
1164 # shellcheck disable=SC2024
1165 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1166 }
1167
1168 p8() { ping "$@" 8.8.8.8; }
1169 p6() { ping6 "$@" 2001:4860:4860::8888; }
1170
1171 pkx() { # package extract
1172 local pkg cached tmp f
1173 c $(mktemp -d)
1174 pkg=$1
1175 # shellcheck disable=SC2012
1176 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1177 if [[ $cached ]]; then
1178 cp $cached .
1179 else
1180 aptitude download $pkg || return 1
1181 fi
1182 tmp=(*); f=${tmp[0]} # only 1 expected
1183 ex $f
1184 rm -f $f
1185 }
1186
1187 # pgrep and kill
1188 pk1() {
1189 local pid
1190 pid=($(pgrep -f "$*"))
1191 case ${#pid[@]} in
1192 1)
1193 # shellcheck disable=SC2128
1194 {
1195 ps -F $pid
1196 m kill $pid
1197 }
1198 ;;
1199 0) echo "no pid found" ;;
1200 *)
1201 ps -F ${pid[@]}
1202 ;;
1203 esac
1204 }
1205
1206 psg () {
1207 local x y help
1208 help="Usage: psg [--help] GREP_ARGS
1209 grep ps and output in a nice format"
1210 if [[ $1 == --help ]]; then
1211 echo "$help"
1212 return
1213 fi
1214 x=$(ps -eF)
1215 # final grep is because some commands tend to have a lot of trailing spaces
1216 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1217 if [[ $y ]]; then
1218 echo "$x" | head -n 1 || [[ $? == 141 ]]
1219 echo "$y"
1220 fi
1221 }
1222
1223 pubip() { curl -4s https://icanhazip.com; }
1224 pubip6() { curl -6s https://icanhazip.com; }
1225 whatismyip() { pubip; }
1226
1227
1228 q() { # start / launch a program in the backround and redir output to null
1229 "$@" &> /dev/null &
1230 }
1231
1232 # shellcheck disable=SC2120
1233 r() {
1234 if [[ $HISTFILE ]]; then
1235 history -a # save history
1236 fi
1237 trap ERR # this avoids a segfault
1238 exit ${1:0}
1239 # i had this redir, not sure why
1240 # exit "$@" 2>/dev/null
1241 }
1242
1243 # scp is insecure and deprecated.
1244 scp() {
1245 rsync --inplace "$@"
1246 }
1247
1248 randport() {
1249 # available high ports are 1024-65535,
1250 # but lets skip things that are more likely to be in use
1251 python3 <<'EOF'
1252 import secrets
1253 print(secrets.SystemRandom().randrange(10002,65500))
1254 EOF
1255 }
1256
1257 # reapply bashrc
1258 reb() {
1259 source ~/.bashrc
1260 }
1261
1262 rl() {
1263 readlink -f "$@"
1264 }
1265 ccomp readlink rl
1266
1267 rsd() {
1268 # rsync, root is required to keep permissions right.
1269 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1270 # --no-times --delete
1271 # basically, make an exact copy, use checksums instead of file times to be more accurate
1272 rsync -ahvic --delete "$@"
1273 }
1274 rsa() {
1275 # like rlu, but dont delete files on the target end which
1276 # do not exist on the original end.
1277 rsync -ahvic "$@"
1278 }
1279 rst() {
1280 # rl without preserving modification time.
1281 rsync -ahvic --delete --no-t "$@"
1282 }
1283 rsu() { # [OPTS] HOST PATH
1284 # eg. rlu -opts frodo /testpath
1285 # relative paths will expanded with readlink -f.
1286 opts=("${@:1:$#-2}") # 1 to last -2
1287 path="${*:$#}" # last
1288 host="${*:$#-1:1}" # last -1
1289 if [[ $path == .* ]]; then
1290 path=$(readlink -f $path)
1291 fi
1292 # rync here uses checksum instead of time so we dont mess with
1293 # unison relying on time as much. g is for group, same reason
1294 # to keep up with unison.
1295 m s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1296 }
1297 ccomp rsync rsd rsa rst rsu
1298
1299 resolvcat() {
1300 local f
1301 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1302 m s nscd -i hosts
1303 fi
1304 f=/etc/resolv.conf
1305 echo $f:; ccat $f
1306 hr; s ss -lpn 'sport = 53'
1307 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1308 # this will fail is dnsmasq is failed
1309 hr; m ser status dnsmasq | cat || :
1310 f=/etc/dnsmasq.conf
1311 hr; echo $f:; ccat $f
1312 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1313 f=/etc/dnsmasq-servers.conf
1314 hr; echo $f:; ccat $f
1315 fi
1316 hr
1317 echo /etc/nsswitch.conf:
1318 grep '^ *hosts:' /etc/nsswitch.conf
1319 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1320 hr; m ser status systemd-resolved | cat || :
1321 hr; m systemd-resolve --status | cat
1322 fi
1323
1324 }
1325 rcat() {
1326 resolvcat | less
1327 }
1328 reresolv() {
1329 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1330 m ser stop nscd
1331 sleep .5
1332 m ser start nscd
1333 m sudo nscd -i hosts
1334 fi
1335 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1336 m sudo systemctl restart dnsmasq
1337 fi
1338 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1339 m sudo systemctl restart systemd-resolved
1340 fi
1341 if type -P resolvectl &>/dev/null; then
1342 resolvectl flush-caches
1343 fi
1344 }
1345
1346 rmstrips() {
1347 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1348 }
1349
1350 s() {
1351 # background
1352 # I use a function because otherwise we cant use in a script,
1353 # cant assign to variable.
1354 #
1355 # note: gksudo is recommended for X apps because it does not set the
1356 # home directory to the same, and thus apps writing to ~ fuck things up
1357 # with root owned files.
1358 #
1359 if [[ $EUID != 0 || $1 == -* ]]; then
1360 # shellcheck disable=SC2034
1361 SUDOD="$PWD" command sudo -i "$@"
1362 DID_SUDO=true
1363 else
1364 "$@"
1365 fi
1366 }
1367 sb() { # sudo bash -c
1368 # use sb instead of s is for sudo redirections,
1369 # eg. sb 'echo "ok fine" > /etc/file'
1370 # shellcheck disable=SC2034
1371 local SUDOD="$PWD"
1372 sudo -i bash -c "$@"
1373 }
1374 ccomp sudo s sb
1375
1376 safe_rename() { # warn and dont rename if file exists.
1377 # mv -n exists, but it\'s silent
1378 if [[ $# != 2 ]]; then
1379 echo safe_rename error: $# args, need 2 >2
1380 return 1
1381 fi
1382 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1383 if [[ -e $2 || -L $2 ]]; then
1384 echo "Cannot rename $1 to $2 as it already exists."
1385 else
1386 mv -vi "$1" "$2"
1387 fi
1388 fi
1389 }
1390
1391
1392 sd() {
1393 sudo dd status=none of="$1"
1394 }
1395
1396 ser() {
1397 if type -p systemctl &>/dev/null; then
1398 s systemctl "$@"
1399 else
1400 if (( $# >= 3 )); then
1401 echo iank: ser expected 2 or less arguments
1402 return 1
1403 fi
1404 s service $2 $1
1405 fi
1406 }
1407 serstat() {
1408 systemctl -n 40 status "$@"
1409 }
1410
1411 seru() { systemctl --user "$@"; }
1412 # like restart, but do nothing if its not already started
1413 srestart() {
1414 local service=$1
1415 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1416 systemctl restart $service
1417 fi
1418 }
1419
1420 setini() { # set a value in a .ini style file
1421 key="$1" value="$2" section="$3" file="$4"
1422 if [[ -s $file ]]; then
1423 sed -ri -f - "$file" <<EOF
1424 # remove existing keys
1425 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1426 # add key
1427 /^\s*\[$section\]/a $key=$value
1428 # from section to eof, do nothing
1429 /^\s*\[$section\]/,\$b
1430 # on the last line, if we haven't found section yet, add section and key
1431 \$a [$section]\\
1432 $key=$value
1433 EOF
1434 else
1435 cat >"$file" <<EOF
1436 [$section]
1437 $key=$value
1438 EOF
1439 fi
1440 }
1441
1442 sgo() { # service go
1443 service=$1
1444 ser restart $service || return 1
1445 if type -p systemctl &>/dev/null; then
1446 ser enable $service
1447 fi
1448 }
1449 soff () {
1450 for service; do
1451 # ignore services that dont exist
1452 if systemctl cat $service &>/dev/null; then
1453 ser stop $service;
1454 ser disable $service
1455 fi
1456 done
1457 }
1458
1459 sgu() {
1460 systemctl list-unit-files | rg "$@"
1461 }
1462
1463
1464 sk() {
1465
1466
1467 # note, if you do something like this
1468 # x=( prefix* )
1469 # then disable the warning with:
1470 # shellcheck disable=SC2206 # globbing is intended
1471
1472 # 2029: "unescaped, this expands on the client side.": yes, I know how ssh works
1473 # 2164: "Use 'cd ... || exit' or 'cd ... || return' in case cd fails.": i have automatic error handling
1474 # 2086: unquoted $var: Quoting every var I set is way too much quotes.
1475 # 2068: Double quote array expansions to avoid re-splitting elements: same as above.
1476 # 2033: command arg is a function name: too many false positives.
1477
1478
1479 # these ones I had disabled, but without a good written explanation, so enabling them temporarily
1480 # 2046: unquoted $(cmd)
1481 # 2119: Functions with optional args get bad warnings when none are passed.
1482
1483 shellcheck -W 999 -x -e 2029,2164,2086,2068,2033 "$@" || return $?
1484 }
1485
1486
1487 # sl: ssh, but firsh rsync our bashrc and related files to a special
1488 # directory on the remote host if needed.
1489
1490 # Some environment variables and files need to be setup for this to work
1491 # (mine are set at the beginning of this file)
1492
1493 # SL_FILES_DIR: Environment variable. Path to folder which should at
1494 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1495 # remote hosts (top level symlinks are resolved) unless the host already
1496 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1497 # control and sync files to separately and already has the ~/.bashrc you
1498 # want. The remote bash will also take its .inputrc config from this
1499 # folder (default of not existing is fine). Mine looks like this:
1500 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1501
1502 # SL_INFO_DIR: Environment variable. This folder stores info about what
1503 # we detected on the remote system and when we last synced. It will be created
1504 # if it does not exist. Sometimes you may want to forget about a
1505 # remote system, you can use sl --rsync, or the function for that slr
1506 # below.
1507
1508 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1509 # depending on the remote host. Run this string on the remote host the
1510 # first time sl is run (or if we run slr). The result is passed to
1511 # SL_TEST_HOOK. For example,
1512 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1513
1514 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1515 # $SL_FILES_DIR to vary the files synced.
1516
1517 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1518 # example to exclude files within a directory. Note, excluded
1519 # files wont be deleted on rsync, you can add --delete-excluded
1520 # to the rsync command if that is desired.
1521
1522 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1523
1524 # For when ~/.bashrc is already customized on the remote server, you
1525 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1526 # commands, even in scripts. This paragraph is all about that. bash
1527 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1528 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1529 # and if you customize it, probably has bugs from time to time. This is
1530 # bad. Here's how I fix it. I have a special condition to "return" in my
1531 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1532 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1533 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1534 # separate file because even if I return early on, the whole file gets
1535 # parsed which can fail if there is a syntax error.
1536 sl() {
1537 # Background on LC_USEBASHRC var (no need to read if you just want to
1538 # use this function): env variables sent across ssh are strictly
1539 # limited, but we get LC_* at least in debian based machines, so we
1540 # just make that * be something no normal program would use. Note, on
1541 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1542 # set, and the inner shell also allows running a nondefault
1543 # .bashrc. This means the outer shell still ran the default .bashrc,
1544 # but that is the best we can do.
1545
1546 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1547 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1548 declare -a args tmpa
1549
1550 args=($SL_SSH_ARGS)
1551
1552 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1553 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1554 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1555 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
1556 # [command]
1557
1558 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
1559 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
1560 # [-F configfile] [-I pkcs11] [-i identity_file]
1561 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
1562 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
1563 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
1564
1565 force_rsync=false
1566 if [[ $1 == --rsync ]]; then
1567 force_rsync=true
1568 shift
1569 fi
1570
1571 sl_test_cmd=$SL_TEST_CMD
1572 sl_test_hook=$SL_TEST_HOOK
1573 sl_rsync_args=$SL_RSYNC_ARGS
1574 while [[ $1 ]]; do
1575 case "$1" in
1576 --rsync)
1577 force_rsync=true
1578 ;;
1579 --sl-test-cmd)
1580 sl_test_cmd="$2"
1581 shift
1582 ;;
1583 --sl-test-hook)
1584 sl_test_hook="$2"
1585 shift
1586 ;;
1587 --sl-rsync-args)
1588 sl_rsync_args="$2"
1589 shift
1590 ;;
1591 *)
1592 break
1593 ;;
1594 esac
1595 shift
1596 done
1597
1598 while [[ $1 ]]; do
1599 case "$1" in
1600 # note we dont support things like -4oOption
1601 -[46AaCfGgKkMNnqsTtVvXxYy]*)
1602 args+=("$1"); shift
1603 ;;
1604 -[bcDEeFIiJLlmOopQRSWw]*)
1605 # -oOption etc is valid
1606 if (( ${#1} >= 3 )); then
1607 args+=("$1"); shift
1608 else
1609 args+=("$1" "$2"); shift 2
1610 fi
1611 ;;
1612 *)
1613 break
1614 ;;
1615 esac
1616 done
1617 remote="$1"
1618 if [[ ! $remote ]]; then
1619 echo $0: error hostname required >&2
1620 return 1
1621 fi
1622 shift
1623
1624 if [[ ! $SL_INFO_DIR ]]; then
1625 echo error: missing '$SL_INFO_DIR' env var >&2
1626 return 1
1627 fi
1628
1629 now=$(date +%s)
1630 dorsync=false
1631 haveinfo=false
1632 tmpa=($SL_INFO_DIR/???????????"$remote")
1633 sshinfo=${tmpa[0]}
1634 if [[ -e $sshinfo ]]; then
1635 if $force_rsync; then
1636 rm -f $sshinfo
1637 else
1638 haveinfo=true
1639 fi
1640 fi
1641 if $haveinfo; then
1642 tmp=${sshinfo[0]##*/}
1643 tmp2=${tmp::11}
1644 type=${tmp2: -1}
1645 extra_info=$(cat $sshinfo)
1646 else
1647 # we test for string to know ssh succeeded
1648 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
1649 testcmd="if $testbool; then printf y; else printf n; fi"
1650 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
1651 echo failed sl test. doing plain ssh -v
1652 command ssh -v "${args[@]}" "$remote"
1653 fi
1654 if [[ $tmp == y* ]]; then
1655 type=a
1656 else
1657 dorsync=true
1658 type=b
1659 fi
1660 extra_info="${tmp:1}"
1661 fi
1662 if [[ $sl_test_hook ]]; then
1663 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
1664 fi
1665
1666 if $haveinfo && [[ $type == b ]]; then
1667 info_sec=${tmp::10}
1668 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
1669 files_sec=${files_sec%%.*}
1670 if (( files_sec > info_sec )); then
1671 dorsync=true
1672 rm -f $sshinfo
1673 fi
1674 fi
1675
1676 sync_dirname=${SL_FILES_DIR##*/}
1677
1678 if [[ ! $SL_FILES_DIR ]]; then
1679 echo error: missing '$SL_FILES_DIR' env var >&2
1680 return 1
1681 fi
1682
1683 if $dorsync; then
1684 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
1685 fi
1686 if $dorsync || ! $haveinfo; then
1687 sshinfo=$SL_INFO_DIR/$now$type"$remote"
1688 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
1689 printf "%s\n" "$extra_info" >$sshinfo
1690 chmod 666 $sshinfo
1691 fi
1692 if [[ $type == b ]]; then
1693 if (( ${#@} )); then
1694 # Theres a couple ways to pass arguments, im not sure whats best,
1695 # but relying on bash 4.4+ escape quoting seems most reliable.
1696 command ssh "${args[@]}" "$remote" \
1697 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
1698 elif [[ ! -t 0 ]]; then
1699 # This case is when commands are being piped to ssh.
1700 # Normally, no bashrc gets sourced.
1701 # But, since we are doing all this, lets source it because we can.
1702 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1703 else
1704 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
1705 fi
1706 else
1707 if [[ -t 0 ]]; then
1708 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
1709 else
1710 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1711 fi
1712 fi
1713 # this function inspired from https://github.com/Russell91/sshrc
1714 }
1715
1716 slr() {
1717 sl --rsync "$@"
1718 }
1719 sss() { # ssh solo
1720 sl -oControlMaster=no -oControlPath=/ "$@"
1721 }
1722 # kill off old shared socket then ssh
1723 ssk() {
1724 m ssh -O exit "$@" || [[ $? == 255 ]]
1725 m sl "$@"
1726 }
1727 ccomp ssh sl slr sss ssk
1728 # plain ssh
1729 ssh() {
1730 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
1731 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
1732 else
1733 LC_USEBASHRC=t command ssh "$@"
1734 fi
1735 }
1736
1737
1738 slog() {
1739 # log with script. timing is $1.t and script is $1.s
1740 # -l to save to ~/typescripts/
1741 # -t to add a timestamp to the filenames
1742 local logdir do_stamp arg_base
1743 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1744 logdir="/a/dt/"
1745 do_stamp=false
1746 while getopts "lt" option
1747 do
1748 case $option in
1749 l ) arg_base=$logdir ;;
1750 t ) do_stamp=true ;;
1751 esac
1752 done
1753 shift $((OPTIND - 1))
1754 arg_base+=$1
1755 [[ -e $logdir ]] || mkdir -p $logdir
1756 $do_stamp && arg_base+=$(date +%F.%T%z)
1757 script -t $arg_base.s 2> $arg_base.t
1758 }
1759 splay() { # script replay
1760 #logRoot="$HOME/typescripts/"
1761 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1762 scriptreplay "$1.t" "$1.s"
1763 }
1764
1765 sr() {
1766 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1767 if [[ $# == 0 ]]; then
1768 sudo -E bash -c -l "$(history -p '!!')"
1769 else
1770 echo this command redos last history item. no argument is accepted
1771 fi
1772 }
1773
1774 srm () {
1775 # with -ll, less secure but faster.
1776 command srm -ll "$@"
1777 }
1778
1779 srun() {
1780 scp $2 $1:/tmp
1781 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1782 }
1783
1784
1785 swap() {
1786 local tmp
1787 tmp=$(mktemp)
1788 mv $1 $tmp
1789 mv $2 $1
1790 mv $tmp $2
1791 }
1792
1793 tclock() { # terminal clock
1794 local x
1795 clear
1796 date +%l:%_M
1797 len=60
1798 # this goes to full width
1799 #len=${1:-$((COLUMNS -7))}
1800 x=1
1801 while true; do
1802 if (( x == len )); then
1803 end=true
1804 d="$(date +%l:%_M) "
1805 else
1806 end=false
1807 d=$(date +%l:%M:%_S)
1808 fi
1809 echo -en "\r"
1810 echo -n "$d"
1811 for ((i=0; i<x; i++)); do
1812 if (( i % 6 )); then
1813 echo -n _
1814 else
1815 echo -n .
1816 fi
1817 done
1818 if $end; then
1819 echo
1820 x=1
1821 else
1822 x=$((x+1))
1823 fi
1824 sleep 5
1825 done
1826 }
1827
1828
1829 te() {
1830 # test existence / exists
1831 local ret=0
1832 for x in "$@"; do
1833 [[ -e "$x" || -L "$x" ]] || ret=1
1834 done
1835 return $ret
1836 }
1837
1838 psoff() {
1839 # normally, i would just execute these commands in the function.
1840 # however, DEBUG is not inherited, so we need to run it outside a function.
1841 # And we want to run set -x afterwards to avoid spam, so we cram everything
1842 # in here, and then it will run after this function is done.
1843 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
1844 }
1845 pson() {
1846 PROMPT_COMMAND=prompt-command
1847 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1848 trap 'settitle "$BASH_COMMAND"' DEBUG
1849 fi
1850 }
1851
1852 tx() { # toggle set -x, and the prompt so it doesnt spam
1853 if [[ $- == *x* ]]; then
1854 set +x
1855 pson
1856 else
1857 psoff
1858 fi
1859 }
1860
1861 psnetns() {
1862 # show all processes in the network namespace $1.
1863 # blank entries appear to be subprocesses/threads
1864 local x netns
1865 netns=$1
1866 ps -w | head -n 1
1867 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1868 while read -r l; do
1869 x=$(ps -w --no-headers -p $l);
1870 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1871 done
1872 }
1873
1874 m() { printf "%s\n" "$*"; "$@"; }
1875
1876 uptime() {
1877 if type -p uprecords &>/dev/null; then
1878 uprecords -B
1879 else
1880 command uptime
1881 fi
1882 }
1883
1884 virshrm() {
1885 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1886 }
1887
1888 vm-set-listen(){
1889 local t
1890 t=$(mktemp)
1891 local vm=$1
1892 local ip=$2
1893 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1894 sed -r "s/listen='[^']+/listen='$ip/"> $t
1895 sudo virsh undefine $vm
1896 sudo virsh define $t
1897 }
1898
1899
1900 vmshare() {
1901 vm-set-listen $1 0.0.0.0
1902 }
1903
1904
1905 vmunshare() {
1906 vm-set-listen $1 127.0.0.1
1907 }
1908
1909 myiwscan() {
1910 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
1911 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
1912 sudo iw dev wls1 scan | sed -rn "
1913 s/^\Wcapability: (.*)/\1/;Ta;h;b
1914 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
1915 # padded to min width of 20
1916 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
1917 "|sort -r
1918 }
1919
1920 # * misc stuff
1921
1922
1923 if $use_color; then
1924
1925 term_bold="$(tput bold)"
1926 term_red="$(tput setaf 1)"
1927 term_green="$(tput setaf 2)"
1928 term_yellow="$(tput setaf 3)"
1929 term_purple="$(tput setaf 5)"
1930 term_nocolor="$(tput sgr0)" # no font attributes
1931
1932 # unused so far. commented for shellcheck
1933 # term_underl="$(tput smul)"
1934 # term_blue="$(tput setaf 4)"
1935 # term_cyan="$(tput setaf 6)"
1936
1937 fi
1938 # Try to keep environment pollution down, EPA loves us.
1939 unset safe_term match_lhs use_color
1940
1941 # * prompt
1942
1943
1944 if [[ $- == *i* ]]; then
1945
1946
1947 case $HOSTNAME in
1948 bk|je|li)
1949 if [[ $EUID == 1000 ]]; then
1950 system-status _ ||:
1951 fi
1952 ;;
1953 esac
1954
1955
1956 # this needs to come before next ps1 stuff
1957 # this stuff needs bash 4, feb 2009,
1958 # old enough to no longer condition on $BASH_VERSION anymore
1959 shopt -s autocd
1960 shopt -s dirspell
1961 PS1='\w'
1962 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
1963 PROMPT_DIRTRIM=2
1964 bind -m vi-command B:shell-backward-word
1965 bind -m vi-command W:shell-forward-word
1966 fi
1967
1968 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1969 unset PROMPT_DIRTRIM
1970 PS1="\h:$PS1"
1971 fi
1972
1973 # emacs terminal has problems if this runs slowly,
1974 # so I've thrown a bunch of things at the wall to speed it up.
1975 prompt-command() {
1976 local return=$? # this MUST COME FIRST
1977 local ps_char ps_color
1978 unset IFS
1979
1980 if [[ $HISTFILE ]]; then
1981 history -a # save history
1982 fi
1983
1984 # assigned in brc2
1985 # shellcheck disable=SC1303
1986 if [[ $jr_pid ]]; then
1987 if [[ -e /proc/$jr_pid ]]; then
1988 kill $jr_pid
1989 fi
1990 unset jr_pid
1991 fi
1992
1993 case $return in
1994 0) ps_color="$term_purple"
1995 ps_char='\$'
1996 ;;
1997 *) ps_color="$term_green"
1998 ps_char="$return \\$"
1999 ;;
2000 esac
2001 if [[ ! -O . ]]; then # not owner
2002 if [[ -w . ]]; then # writable
2003 ps_color="$term_bold$term_red"
2004 else
2005 ps_color="$term_bold$term_green"
2006 fi
2007 fi
2008
2009 # faster than sourceing the file im guessing
2010 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2011 eval $(< /dev/shm/iank-status)
2012 fi
2013 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
2014 ps_char="@ $ps_char"
2015 fi
2016 # We could test if sudo is active with sudo -nv
2017 # but then we get an email and log of lots of failed sudo commands.
2018 # We could turn those off, but seems better not to.
2019 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2020 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2021 fi
2022 if [[ ! $HISTFILE ]]; then
2023 ps_char="NOHIST $ps_char"
2024 fi
2025 PS1="${PS1%"${PS1#*[wW]}"} $psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2026
2027 # set titlebar. instead, using more advanced
2028 # titelbar below
2029 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2030 }
2031 PROMPT_COMMAND=prompt-command
2032
2033 if [[ $TERM == screen* ]]; then
2034 _title_escape="\033]..2;"
2035 else
2036 # somme sites recommend this, i dunno what the diff is.
2037 #_title_escape="\033]30;"
2038 _title_escape="\033]0;"
2039 fi
2040
2041 settitle () {
2042 # this makes it so we show the current command if
2043 # one is running, otherwise, show nothing
2044
2045 if [[ $1 == prompt-command ]]; then
2046 return 0
2047 fi
2048 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
2049 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2050 printf "%s" "$*"
2051 echo -ne "\007"
2052 fi
2053 }
2054
2055 # note, this wont work:
2056 # x=$(mktemp); cp a $x
2057 # I havnt figured out why, bigger fish to fry.
2058 #
2059 # for titlebar.
2060 # condition from the screen man page i think.
2061 # note: duplicated in tx()
2062 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2063 trap 'settitle "$BASH_COMMAND"' DEBUG
2064 else
2065 trap DEBUG
2066 fi
2067
2068 fi
2069
2070 # * stuff that makes sense to be at the end
2071
2072
2073 # best practice
2074 unset IFS
2075
2076 # shellcheck disable=SC1090
2077 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2078
2079 # I had this idea to start a bash shell which would run an initial
2080 # command passed through this env variable, then continue on
2081 # interactively. But the use case I had in mind went away.
2082 #
2083 # if [[ $MY_INIT_CMD ]]; then
2084 # "${MY_INIT_CMD[@]}"
2085 # unset MY_INIT_CMD
2086 # fi
2087
2088 # ensure no bad programs appending to this file will have an affect
2089 return 0