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