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