mostly fixes, some 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 x() { builtin kill %%; }
871
872 dc() {
873 diff --strip-trailing-cr -w "$@" # diff content
874 }
875 ccomp diff dc
876
877 despace() {
878 local x y
879 for x in "$@"; do
880 y="${x// /_}"
881 safe_rename "$x" "$y"
882 done
883 }
884
885 # df progress
886 # usage: dfp MOUNTPOINT [SECOND_INTERVAL]
887 # SECOND_INTERVAL defaults to 90
888 dfp() {
889 # mp = mountpoint
890 local a b mp interval
891 mp=$1
892 interval=${2:-90}
893 if [[ ! $mp ]]; then
894 echo "dfp: error, missing 1st arg" >&2
895 return 1
896 fi
897 while true; do
898 a=$(df --output=used $mp | tail -n1)
899 sleep $interval
900 b=$(df --output=used $mp | tail -n1)
901 printf "used mib: %'d mib/min: %s\n" $(( b /1000 )) $(( (b-a) / (interval * 1000 / 60 ) ))
902 done
903 }
904
905 # get ipv4 ip from HOST. or if it is already a number, return that
906 hostip() {
907 local host="$1"
908 case $host in
909 [0-9:])
910 echo "$host"
911 ;;
912 *)
913 getent ahostsv4 "$host" | awk '{ print $1 }' | head -n1
914 ;;
915 esac
916 }
917
918 dig() {
919 command dig +nostats +nocmd "$@"
920 }
921 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
922 digsort() {
923 local sec
924 sec=
925 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
926 if [[ $l == [^\;]* ]]; then
927 sec+="$l"$'\n'
928 else
929 if [[ $sec ]]; then
930 printf "%s" "$sec" | sort
931 sec=
932 fi
933 printf "%s\n" "$l"
934 fi
935 done
936 }
937 ccomp dig digsort
938 # compare digs to the 2 servers
939 # usage: digdiff @server1 @server2 DIG_ARGS
940 # note: only the soa master nameserver will respond with
941 # ra "recursive answer" flag. That difference is meaningless afaik.
942 digdiff() {
943 local s1 s2
944 s1=$1
945 shift
946 s2=$1
947 shift
948 digsort $s1 "$@" | tee /tmp/digdiff
949 diff -u /tmp/digdiff <(digsort $s2 "$@")
950 }
951
952 dt() {
953 date "+%A, %B %d, %r" "$@"
954 }
955 dtr() {
956 date -R "$@"
957 }
958 ccomp date dt dtr
959
960 dus() { # du, sorted, default arg of
961 du -sh ${@:-*} | sort -h
962 }
963 ccomp du dus
964
965
966 e() { printf "%s\n" "$*"; }
967
968 # echo args
969 ea() {
970 if (( ! $# )); then
971 echo no args
972 fi
973 for arg; do
974 printf "%qEOL\n" "${arg}"
975 printf "%s" "${arg}" |& hexdump -C
976 done
977 }
978
979 # echo variables. print var including escapes, etc, like xxd for variable
980 ev() {
981 if (( ! $# )); then
982 echo no args
983 fi
984 for arg; do
985 if [[ -v $arg ]]; then
986 printf "%qEOL\n" "${!arg}"
987 printf "%s" "${!arg}" |& hexdump -C
988 else
989 echo arg $arg is unset
990 fi
991 done
992 }
993
994 ediff() {
995 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
996 emacs --eval "(ediff-files \"$1\" \"$2\")"
997 }
998
999 # mail related
1000 etail() {
1001 ngset
1002 tail -F /var/log/exim4/mainlog /var/log/exim4/*main /var/log/exim4/paniclog /var/log/exim4/*panic -n 200 "$@"
1003 ngreset
1004 }
1005 etailm() {
1006 tail -F /var/log/exim4/mainlog -n 200 "$@"
1007 }
1008 etail2() {
1009 tail -F /var/log/exim4/mymain -n 200 "$@"
1010 }
1011 ccomp tail etail etail2
1012
1013
1014
1015
1016 # print exim old pids
1017 eoldpids() {
1018 local configtime pid piduptime now daemonpid
1019 printf -v now '%(%s)T' -1
1020 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
1021 if [[ -s /run/exim4/exim.pid ]]; then
1022 daemonpid=$(cat /run/exim4/exim.pid)
1023 fi
1024 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
1025 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
1026 if [[ $pid == $daemonpid ]]; then
1027 continue
1028 fi
1029 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
1030 if (( configtime > now - piduptime )); then
1031 echo $pid
1032 fi
1033 done
1034 }
1035
1036 # exim tail but only watch lines from new pids
1037 etailnew() {
1038 local pid oldpids
1039 for pid in $(eoldpids); do
1040 oldpids+="$pid|"
1041 done
1042 if [[ $oldpids ]]; then
1043 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
1044 else
1045 etail
1046 fi
1047 }
1048 # exim watch as old pids go away
1049 ewatchold() {
1050 local configtime pid piduptime now
1051 local -i count
1052 local -a oldpids
1053 count=0
1054 while true; do
1055 oldpids=($(eoldpids))
1056 if (( ! ${#oldpids[@]} )); then
1057 return
1058 fi
1059 # print the date every 20 iterations
1060 if (( ! count % 20 )); then
1061 date
1062 fi
1063 count+=1
1064 ps -f -p "${oldpids[*]}"
1065 sleep 1
1066 done
1067 }
1068
1069 eless() {
1070 less /var/log/exim4/mainlog
1071 }
1072 ccomp less eless
1073 eqcat() {
1074 exiqgrep -ir.\* -o 60 | while read -r i; do
1075 hlm exim -Mvc $i
1076 echo
1077 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
1078 done
1079 }
1080 eqrmf() {
1081 # other ways to get the list of message ids:
1082 # exim -bp | awk 'NF == 4 {print $3}'
1083 # # this is slower 160ms, vs 60.
1084 # exipick -i
1085 exiqgrep -ir.\* | xargs exim -Mrm
1086 }
1087
1088 econfdevnew() {
1089 rm -rf /tmp/edev
1090 mkdir -p /tmp/edev/etc
1091 cp -ra /etc/exim4 /tmp/edev/etc
1092 cp -ra /etc/alias* /tmp/edev/etc
1093 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
1094 econfdev
1095 }
1096 econfdev() {
1097 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
1098 }
1099
1100
1101
1102
1103 fa() {
1104 # find array. make an array of file names found by find into $x
1105 # argument: find arguments
1106 # return: find results in an array $x
1107 while read -rd ''; do
1108 x+=("$REPLY");
1109 done < <(find "$@" -print0);
1110 }
1111
1112 faf() { # find all files. use -L to follow symlinks
1113 find "$@" -not \( -name .svn -prune -o -name .git -prune \
1114 -o -name .hg -prune -o -name .editor-backups -prune \
1115 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
1116 }
1117
1118 # full path without resolving symlinks
1119 fp() {
1120 local dir base
1121 base="${1##*/}"
1122 dir="${1%$base}"
1123 printf "%s/%s\n" $(cd $dir; pwd) "$base"
1124 }
1125
1126
1127 # mail related
1128 frozen() {
1129 rm -rf /tmp/frozen
1130 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
1131 sudo exim -Mvl $id
1132 echo
1133 sudo exim -Mvh $id
1134 echo
1135 sudo exim -Mvb $id
1136 echo -e '\n\n##############################\n'
1137 done | tee -a /tmp/frozen
1138 }
1139 frozenrm() {
1140 local ids=()
1141 while read -r line; do
1142 printf '%s\n' "$line"
1143 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
1144 done < <(s mailq)
1145 echo "sleeping for 2 in case you change your mind"
1146 sleep 2
1147 sudo exim -Mrm "${ids[@]}"
1148 }
1149
1150 funce() {
1151 # like -e for functions. returns on error.
1152 # at the end of the function, disable with:
1153 # trap ERR
1154 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
1155 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
1156 trap ERR
1157 return' ERR
1158 }
1159
1160 getdir () {
1161 local help="Usage: getdir [--help] PATH
1162 Output the directory of PATH, or just PATH if it is a directory."
1163 if [[ $1 == --help ]]; then
1164 echo "$help"
1165 return 0
1166 fi
1167 if [[ $# -ne 1 ]]; then
1168 echo "getdir error: expected 1 argument, got $#"
1169 return 1
1170 fi
1171 if [[ -d $1 ]]; then
1172 echo "$1"
1173 else
1174 local dir
1175 dir="$(dirname "$1")"
1176 if [[ -d $dir ]]; then
1177 echo "$dir"
1178 else
1179 echo "getdir error: directory does not exist"
1180 return 1
1181 fi
1182 fi
1183 }
1184
1185 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
1186 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
1187 local root
1188 root=$(gitroot) || return 1 # function to set gitroot
1189 builtin cd "$root"
1190 git symbolic-ref HEAD refs/heads/$1
1191 rm .git/index
1192 git clean -fdx
1193 }
1194
1195 # shellcheck disable=SC2120
1196 gitroot() {
1197 local help="Usage: gitroot [--help]
1198 Print the full path to the root of the current git repo
1199
1200 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
1201 and works in older versions of git which did not have that."
1202 if [[ $1 == --help ]]; then
1203 echo "$help"
1204 return
1205 fi
1206 local p
1207 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
1208 [[ $p != /* ]] && p=$PWD
1209 echo "${p%%/.git}"
1210 }
1211
1212 g() {
1213
1214 # todo: patch emacs so it will look elsewhere. this is kinda sad:
1215 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
1216
1217 local args gdb=false
1218
1219 if [[ $EMACSDIR ]]; then
1220 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
1221 fi
1222
1223 if [[ $DISPLAY ]]; then
1224 args=-n
1225 fi
1226
1227 if (( $# == 0 )); then
1228 args+=" -c"
1229 fi
1230 # duplicate -c, but oh well
1231 if ! pgrep -u $EUID emacsclient; then
1232 if (( $# == 0 )) && type -p gdb &>/dev/null; then
1233 gdb=true
1234 else
1235 args+=" -c"
1236 fi
1237 fi
1238 if [[ $EMACSDIR ]]; then
1239 # Alter the path here, otherwise the nfs mount gets triggered on the
1240 # first path lookup when emacs is not being used.
1241 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
1242 else
1243 if $gdb; then
1244 # due to a bug, we cant debug from the start unless we get a new gdb
1245 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
1246 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
1247 m emacsclient -a "" $args "$@"
1248 sleep 1
1249 cd /a/opt/emacs-$(distro-name)$(distro-num)
1250 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
1251 cd -
1252 else
1253 m emacsclient -a "" $args "$@"
1254 fi
1255 fi
1256 }
1257
1258 # force terminal version
1259 gn() {
1260 g -n "$@"
1261 }
1262
1263 gmacs() {
1264 # quit will prompt if the program crashes.
1265 gdb -ex=r -ex=quit --args emacs "$@"; r;
1266 }
1267
1268 gdkill() {
1269 # kill the emacs daemon
1270 pk1 emacs --daemon
1271 }
1272
1273 gr() {
1274 grep -iIP --color=auto "$@" || return $?
1275 }
1276 grr() { # grep recursive
1277 # Don't return 1 on nonmatch because this is meant to be
1278 # interactive, not in a conditional.
1279 if [[ ${#@} == 1 ]]; then
1280 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
1281 else
1282 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
1283 fi
1284 }
1285 ccomp grep gr grr
1286
1287 rg() { grr "$@"; }
1288 ccomp grep rg
1289
1290 hr() { # horizontal row. used to break up output
1291 printf "$(tput setaf 5 2>/dev/null ||:)█$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
1292 echo
1293 }
1294 # highlight
1295 hl() {
1296 local col input_len=0
1297 for arg; do
1298 input_len=$((input_len + 1 + ${#arg}))
1299 done
1300 col=$((60 - input_len))
1301 printf "\e[1;97;41m%s" "$*"
1302 if (( col > 0 )); then
1303 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
1304 fi
1305 echo
1306 }
1307 hlm() { hl "$*"; "$@"; }
1308
1309 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
1310
1311
1312 # get latest hub and run it
1313 # main command to use:
1314 # hub pull-request --no-edit
1315 # --no-edit means to use the first commit\'s message as the pull request message.
1316 # If that fails, try doing
1317 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
1318 # where branch is usually master. it does the pr against your current branch.
1319 #
1320 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1321 # it\'s at ~/.config/hub
1322 hub() {
1323 local up uptar updir p v
1324 # example https://github.com/github/hub/releases/download/v2.14.2/hub-linux-amd64-2.14.2.tgz
1325 up=$(wget -q -O- https://api.github.com/repos/github/hub/releases/latest | jq -r .assets[].browser_download_url | grep linux-amd64)
1326 re='[[:space:]]'
1327 if [[ ! $up || $up == $re ]]; then
1328 echo "failed to get good update url. got: $up"
1329 fi
1330 uptar=${up##*/}
1331 updir=${uptar%.tgz}
1332 if [[ ! -e /a/opt/$updir ]]; then
1333 rm -rf /a/opt/hub-linux-amd64*
1334 wget -P /a/opt $up
1335 tar -C /a/opt -zxf /a/opt/$uptar
1336 rm -f /a/opt/$uptar
1337 fi
1338 if ! which hub &>/dev/null; then
1339 sudo /a/opt/$updir/install
1340 fi
1341
1342 # save token across computers
1343 if [[ ! -L ~/.config/hub ]]; then
1344 if [[ -e ~/.config/hub ]]; then
1345 mv ~/.config/hub /p/c/subdir_files/.config/
1346 fi
1347 if [[ -e /p/c/subdir_files/.config/hub ]]; then
1348 conflink
1349 fi
1350 fi
1351 command hub "$@"
1352 }
1353
1354 i() { git "$@"; }
1355 ccomp git i
1356
1357 # git status:
1358 # cvs -qn update
1359
1360 # git checkout FILE
1361 # cvs update -C FILE
1362
1363 # git pull
1364 # cvs up[date]
1365
1366 # potentially useful command translation
1367 # https://fling.seas.upenn.edu/~giesen/dynamic/wordpress/equivalent-commands-for-git-svn-and-cvs/
1368
1369 # importing cvs repo into git using git-cvs package:
1370 # /f/www $ /usr/lib/git-core/git-cvsimport -C /f/www-git
1371
1372 ic() {
1373 # fast commit all
1374 git commit -am "$*"
1375 }
1376
1377 ipp() {
1378 git pull
1379 git push
1380 }
1381
1382
1383 ifn() {
1384 # insensitive find
1385 # -L = follow symlinks
1386 find -L . -not \( -name .svn -prune -o -name .git -prune \
1387 -o -name .hg -prune -o -name .editor-backups -prune \
1388 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1389 }
1390
1391 ifd() {
1392 # insensitive find directory
1393 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
1394 -o -name .hg -prune -o -name .editor-backups -prune \
1395 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1396 }
1397
1398
1399 ipdrop() {
1400 sudo iptables -A INPUT -s $1 -j DROP
1401 }
1402
1403
1404 istext() {
1405 grep -Il "" "$@" &>/dev/null
1406 }
1407
1408 pst() {
1409 pstree -apnA
1410 }
1411
1412 jtail() {
1413 journalctl -n 10000 -f "$@"
1414 }
1415 jr() { journalctl "$@" ; }
1416 jrf() { journalctl -f "$@" ; }
1417 jru() {
1418 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
1419 }
1420
1421
1422
1423 l() {
1424 if [[ $PWD == /[iap] ]]; then
1425 command ls -A --color=auto -I lost+found "$@"
1426 else
1427 command ls -A --color=auto "$@"
1428 fi
1429 }
1430
1431 lcn() { locate -i "*$**"; }
1432
1433 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
1434
1435 lt() { ll -tr "$@"; }
1436
1437 lld() { ll -d "$@"; }
1438
1439 ccomp ls l lg lt lld ll
1440
1441 # low recursively
1442 lowr() {
1443 local f dirs i a
1444 local -a all
1445 for dirs in false true; do
1446 for f; do
1447 if [[ -d $f ]]; then
1448 all=("$f"/**)
1449 # reverse the order to rename the nested dirs first.
1450 # note: 0 element is the dir itself
1451 for ((i=${#all[@]}-1; i>=1; i--)); do
1452 a="${all[i]}"
1453 if $dirs && [[ -d $a ]]; then
1454 # e dirs low "$a" # debug
1455 low "$a"
1456 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1457 # debug
1458 # e not dirs low "$a" # debug
1459 low "$a"
1460 fi
1461 done
1462 fi
1463 # just rename all the top level args on the second pass
1464 if $dirs; then
1465 # e final dirs low "$f" # debug
1466 low "$f"
1467 fi
1468 done
1469 done
1470 }
1471
1472 low() { # make filenames lowercase, remove bad chars
1473 local arg new dir f
1474 for arg; do
1475 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1476 dir="${arg%/*}"
1477 if (( ${#dir} == ${#arg} )); then
1478 dir=.
1479 fi
1480 f="${arg##*/}"
1481 new="${f,,}" # downcase
1482 new="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1483 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1484 new="${new%"${new##*[[:alnum:]]}"}"
1485 # remove bad underscores, like __ and _._
1486 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1487 safe_rename "$dir/$f" "$dir/$new" || return 1
1488 done
1489 return 0
1490 }
1491
1492 lower() { # make first letter of filenames lowercase.
1493 local x
1494 for x in "$@"; do
1495 if [[ ${x::1} == [A-Z] ]]; then
1496 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1497 safe_rename "$x" "$y" || return 1
1498 fi
1499 done
1500 }
1501
1502
1503 k() { # history search
1504 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1505 }
1506 ks() { # history search with context
1507 # args are an extended regex used by sed
1508 history | sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" | tail -n 80 || [[ $? == 1 ]];
1509 }
1510 ksu() { # history search unique
1511 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1512 }
1513
1514 # todo: id like to do maybe a daily or hourly cronjob to
1515 # check that my history file size is increasing. Ive had it
1516 # inexplicably truncated in the past.
1517 histrm() {
1518 history -n
1519 HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1520 read -p "press anything but contrl-c to delete"
1521 for entry in $(HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' | tac); do
1522 history -d $entry
1523 done
1524 history -w
1525 }
1526
1527 ccomp grep k ks ksu histrm
1528
1529
1530 make-targets() {
1531 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1532 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1533 }
1534
1535 mkc() {
1536 mkdir "$1"
1537 c "$1"
1538 }
1539 ccomp mkdir mkc
1540
1541 mkct() {
1542 mkc $(mktemp -d)
1543 }
1544
1545 mkt() { # mkdir and touch file
1546 local path="$1"
1547 mkdir -p "$(dirname "$path")"
1548 touch "$path"
1549 }
1550
1551 # shellcheck disable=SC2032
1552 mkdir() { command mkdir -p "$@"; }
1553
1554 nags() {
1555 # https://github.com/HenriWahl/Nagstamon/issues/357
1556 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1557 /usr/lib/notification-daemon/notification-daemon &
1558 fi
1559 /usr/bin/nagstamon &
1560 }
1561
1562 nmt() {
1563 # cant use s because sudo -i doesnt work for passwordless sudo command
1564 case $EUID in
1565 0)
1566 sudo nmtui-connect "$@"
1567 ;;
1568 *)
1569 nmtui-connect "$@"
1570 ;;
1571 esac
1572 }
1573
1574
1575 ngset() {
1576 if shopt nullglob >/dev/null; then
1577 ngreset=false
1578 else
1579 shopt -s nullglob
1580 ngreset=true
1581 fi
1582 }
1583 ngreset() {
1584 if $ngreset; then
1585 shopt -u nullglob
1586 fi
1587 }
1588
1589 nopanic() {
1590 # shellcheck disable=SC2024
1591 ngset
1592 for f in /var/log/exim4/paniclog /var/log/exim4/*panic; do
1593 base=${f##*/}
1594 if [[ -s $f ]]; then
1595 echo ================== $f =============
1596 s tee -a /var/log/exim4/$base-archive <$f
1597 s truncate -s0 $f
1598 fi
1599 done
1600 ngreset
1601 }
1602
1603
1604 ping() { command ping -O "$@"; }
1605 p8() { ping "$@" 8.8.8.8; }
1606 p6() { ping6 "$@" 2001:4860:4860::8888; }
1607
1608 pkx() { # package extract
1609 local pkg cached tmp f
1610 c $(mktemp -d)
1611 pkg=$1
1612 # shellcheck disable=SC2012
1613 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1614 if [[ $cached ]]; then
1615 cp $cached .
1616 else
1617 aptitude download $pkg || return 1
1618 fi
1619 tmp=(*); f=${tmp[0]} # only 1 expected
1620 ex $f
1621 rm -f $f
1622 }
1623
1624 # pgrep and kill
1625 pk1() {
1626 local pid
1627 pid=($(pgrep -f "$*"))
1628 case ${#pid[@]} in
1629 1)
1630 # shellcheck disable=SC2128
1631 {
1632 ps -F $pid
1633 m kill $pid
1634 }
1635 ;;
1636 0) echo "no pid found" ;;
1637 *)
1638 ps -F ${pid[@]}
1639 ;;
1640 esac
1641 }
1642
1643 psg () {
1644 local x y help
1645 help="Usage: psg [--help] GREP_ARGS
1646 grep ps and output in a nice format"
1647 if [[ $1 == --help ]]; then
1648 echo "$help"
1649 return
1650 fi
1651 x=$(ps -eF)
1652 # final grep is because some commands tend to have a lot of trailing spaces
1653 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1654 if [[ $y ]]; then
1655 echo "$x" | head -n 1 || [[ $? == 141 ]]
1656 echo "$y"
1657 fi
1658 }
1659
1660 pubip() { curl -4s https://icanhazip.com; }
1661 pubip6() { curl -6s https://icanhazip.com; }
1662 whatismyip() { pubip; }
1663
1664
1665 q() { # start / launch a program in the backround and redir output to null
1666 "$@" &> /dev/null &
1667 }
1668
1669 # shellcheck disable=SC2120
1670 r() {
1671 if [[ $HISTFILE ]]; then
1672 history -a # save history
1673 fi
1674 trap ERR # this avoids a segfault
1675 exit ${1:0}
1676 # i had this redir, not sure why
1677 # exit "$@" 2>/dev/null
1678 }
1679
1680 # scp is insecure and deprecated.
1681 scp() {
1682 rsync --inplace "$@"
1683 }
1684 ccomp rsync scp
1685
1686 randport() {
1687 # available high ports are 1024-65535,
1688 # but lets skip things that are more likely to be in use
1689 python3 <<'EOF'
1690 import secrets
1691 print(secrets.SystemRandom().randrange(10002,65500))
1692 EOF
1693 }
1694
1695 # reapply bashrc
1696 reb() {
1697 source ~/.bashrc
1698 }
1699
1700 rl() {
1701 readlink -f "$@"
1702 }
1703 ccomp readlink rl
1704
1705 rsd() {
1706 # rsync, root is required to keep permissions right.
1707 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1708 # --no-times --delete
1709 # basically, make an exact copy, use checksums instead of file times to be more accurate
1710 rsync -ahvic --delete "$@"
1711 }
1712 rsa() {
1713 # like rlu, but dont delete files on the target end which
1714 # do not exist on the original end.
1715 rsync -ahvic "$@"
1716 }
1717 rst() {
1718 # rl without preserving modification time.
1719 rsync -ahvic --delete --no-t "$@"
1720 }
1721 # [RSYNC_OPTS] HOST PATH
1722 rsu() {
1723 # eg. rsu -opts frodo /testpath
1724 # relative paths will expanded with readlink -f.
1725 opts=("${@:1:$#-2}") # 1 to last -2
1726 path="${*:$#}" # last
1727 host="${*:$#-1:1}" # last -1
1728 if [[ $path == .* ]]; then
1729 path=$(readlink -f $path)
1730 fi
1731 m rsync -ahvi --relative --no-implied-dirs "${opts[@]}" "$path" "root@$host:/";
1732 }
1733 ccomp rsync rsd rsa rst rsu
1734
1735 # find programs listening on a port
1736 ssp() {
1737 local port=$1
1738 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
1739 s ss -lpn state listening sport = $port
1740 }
1741
1742 resolvcat() {
1743 local f
1744 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1745 m s nscd -i hosts
1746 fi
1747 f=/etc/resolv.conf
1748 echo $f:; ccat $f
1749 hr; s ss -lpn sport = 53
1750 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1751 # this will fail is dnsmasq is failed
1752 hr; m ser status dnsmasq | cat || :
1753 f=/etc/dnsmasq.conf
1754 hr; echo $f:; ccat $f
1755 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1756 f=/etc/dnsmasq-servers.conf
1757 hr; echo $f:; ccat $f
1758 fi
1759 hr
1760 echo /etc/nsswitch.conf:
1761 grep '^ *hosts:' /etc/nsswitch.conf
1762 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1763 hr; m ser status systemd-resolved | cat || :
1764 hr; m resolvectl status | cat
1765 fi
1766
1767 }
1768 rcat() {
1769 resolvcat | less
1770 }
1771 reresolv() {
1772 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1773 m ser stop nscd
1774 sleep .5
1775 m ser start nscd
1776 m sudo nscd -i hosts
1777 fi
1778 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1779 m sudo systemctl restart dnsmasq
1780 fi
1781 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1782 m sudo systemctl restart systemd-resolved
1783 fi
1784 if type -P resolvectl &>/dev/null; then
1785 resolvectl flush-caches
1786 fi
1787 }
1788
1789 rmstrips() {
1790 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1791 }
1792
1793 urun () {
1794 umask $1
1795 shift
1796 "$@"
1797 }
1798 sudo () {
1799 command sudo "$@" || return $?
1800 DID_SUDO=true
1801 }
1802 s() {
1803 # background
1804 # I use a function because otherwise we cant use in a script,
1805 # cant assign to variable.
1806 #
1807 # note: gksudo is recommended for X apps because it does not set the
1808 # home directory to the same, and thus apps writing to ~ fuck things up
1809 # with root owned files.
1810 #
1811 if [[ $EUID != 0 || $1 == -* ]]; then
1812 # shellcheck disable=SC2034
1813 SUDOD="$PWD" command sudo -i "$@"
1814 DID_SUDO=true
1815 else
1816 "$@"
1817 fi
1818 }
1819 sb() { # sudo bash -c
1820 # use sb instead of s is for sudo redirections,
1821 # eg. sb 'echo "ok fine" > /etc/file'
1822 # shellcheck disable=SC2034
1823 local SUDOD="$PWD"
1824 sudo -i bash -c "$@"
1825 }
1826 # secret sudo
1827 se() { s urun 0077 "$@"; }
1828 ccomp sudo s sb se
1829
1830 safe_rename() { # warn and dont rename if file exists.
1831 # mv -n exists, but it\'s silent
1832 if [[ $# != 2 ]]; then
1833 echo safe_rename error: $# args, need 2 >2
1834 return 1
1835 fi
1836 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1837 if [[ -e $2 || -L $2 ]]; then
1838 echo "Cannot rename $1 to $2 as it already exists."
1839 else
1840 mv -vi "$1" "$2"
1841 fi
1842 fi
1843 }
1844
1845
1846 sd() {
1847 sudo dd status=none of="$1"
1848 }
1849
1850 ser() {
1851 if type -p systemctl &>/dev/null; then
1852 s systemctl "$@"
1853 else
1854 if (( $# >= 3 )); then
1855 echo iank: ser expected 2 or less arguments
1856 return 1
1857 fi
1858 s service $2 $1
1859 fi
1860 }
1861 serstat() {
1862 systemctl -n 40 status "$@"
1863 }
1864
1865 seru() { systemctl --user "$@"; }
1866 # like restart, but do nothing if its not already started
1867 srestart() {
1868 local service=$1
1869 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1870 systemctl restart $service
1871 fi
1872 }
1873
1874 setini() { # set a value in a .ini style file
1875 key="$1" value="$2" section="$3" file="$4"
1876 if [[ -s $file ]]; then
1877 sed -ri -f - "$file" <<EOF
1878 # remove existing keys
1879 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1880 # add key
1881 /^\s*\[$section\]/a $key=$value
1882 # from section to eof, do nothing
1883 /^\s*\[$section\]/,\$b
1884 # on the last line, if we haven't found section yet, add section and key
1885 \$a [$section]\\
1886 $key=$value
1887 EOF
1888 else
1889 cat >"$file" <<EOF
1890 [$section]
1891 $key=$value
1892 EOF
1893 fi
1894 }
1895
1896 sgo() { # service go
1897 service=$1
1898 ser restart $service || return 1
1899 if type -p systemctl &>/dev/null; then
1900 ser enable $service
1901 fi
1902 }
1903 soff () {
1904 for service; do
1905 # ignore services that dont exist
1906 if systemctl cat $service &>/dev/null; then
1907 ser stop $service;
1908 ser disable $service
1909 fi
1910 done
1911 }
1912
1913 sgu() {
1914 systemctl list-unit-files | rg "$@"
1915 }
1916
1917
1918 sk() {
1919
1920
1921 # disable a warning with:
1922 # shellcheck disable=SC2206 # reasoning
1923
1924 # see bash-template/style-guide.md for justifications
1925
1926 local quotes others
1927 quotes=2048,2068,2086,2206
1928 others=2029,2033,2054,2164
1929 shellcheck -W 999 -x -e $quotes,$others "$@" || return $?
1930 }
1931
1932
1933 # sl: ssh, but firsh rsync our bashrc and related files to a special
1934 # directory on the remote host if needed.
1935
1936 # Some environment variables and files need to be setup for this to work
1937 # (mine are set at the beginning of this file)
1938
1939 # SL_FILES_DIR: Environment variable. Path to folder which should at
1940 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1941 # remote hosts (top level symlinks are resolved) unless the host already
1942 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1943 # control and sync files to separately and already has the ~/.bashrc you
1944 # want. The remote bash will also take its .inputrc config from this
1945 # folder (default of not existing is fine). Mine looks like this:
1946 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1947
1948 # SL_INFO_DIR: Environment variable. This folder stores info about what
1949 # we detected on the remote system and when we last synced. It will be created
1950 # if it does not exist. Sometimes you may want to forget about a
1951 # remote system, you can use sl --rsync, or the function for that slr
1952 # below.
1953
1954 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1955 # depending on the remote host. Run this string on the remote host the
1956 # first time sl is run (or if we run slr). The result is passed to
1957 # SL_TEST_HOOK. For example,
1958 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1959
1960 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1961 # $SL_FILES_DIR to vary the files synced.
1962
1963 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1964 # example to exclude files within a directory. Note, excluded
1965 # files wont be deleted on rsync, you can add --delete-excluded
1966 # to the rsync command if that is desired.
1967
1968 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1969
1970 # For when ~/.bashrc is already customized on the remote server, you
1971 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1972 # commands, even in scripts. This paragraph is all about that. bash
1973 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1974 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1975 # and if you customize it, probably has bugs from time to time. This is
1976 # bad. Here's how I fix it. I have a special condition to "return" in my
1977 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1978 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1979 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1980 # separate file because even if I return early on, the whole file gets
1981 # parsed which can fail if there is a syntax error.
1982 sl() {
1983 # Background on LC_USEBASHRC var (no need to read if you just want to
1984 # use this function): env variables sent across ssh are strictly
1985 # limited, but we get LC_* at least in debian based machines, so we
1986 # just make that * be something no normal program would use. Note, on
1987 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1988 # set, and the inner shell also allows running a nondefault
1989 # .bashrc. This means the outer shell still ran the default .bashrc,
1990 # but that is the best we can do.
1991
1992 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1993 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1994 declare -a args tmpa
1995
1996 args=($SL_SSH_ARGS)
1997
1998 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1999 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
2000 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
2001 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
2002 # [command]
2003
2004 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
2005 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
2006 # [-F configfile] [-I pkcs11] [-i identity_file]
2007 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
2008 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
2009 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
2010
2011 force_rsync=false
2012 if [[ $1 == --rsync ]]; then
2013 force_rsync=true
2014 shift
2015 fi
2016
2017 sl_test_cmd=$SL_TEST_CMD
2018 sl_test_hook=$SL_TEST_HOOK
2019 sl_rsync_args=$SL_RSYNC_ARGS
2020 while [[ $1 ]]; do
2021 case "$1" in
2022 --rsync)
2023 force_rsync=true
2024 ;;
2025 --sl-test-cmd)
2026 sl_test_cmd="$2"
2027 shift
2028 ;;
2029 --sl-test-hook)
2030 sl_test_hook="$2"
2031 shift
2032 ;;
2033 --sl-rsync-args)
2034 sl_rsync_args="$2"
2035 shift
2036 ;;
2037 *)
2038 break
2039 ;;
2040 esac
2041 shift
2042 done
2043
2044 while [[ $1 ]]; do
2045 case "$1" in
2046 # note we dont support things like -4oOption
2047 -[46AaCfGgKkMNnqsTtVvXxYy]*)
2048 args+=("$1"); shift
2049 ;;
2050 -[bcDEeFIiJLlmOopQRSWw]*)
2051 # -oOption etc is valid
2052 if (( ${#1} >= 3 )); then
2053 args+=("$1"); shift
2054 else
2055 args+=("$1" "$2"); shift 2
2056 fi
2057 ;;
2058 *)
2059 break
2060 ;;
2061 esac
2062 done
2063 remote="$1"
2064 if [[ ! $remote ]]; then
2065 echo $0: error hostname required >&2
2066 return 1
2067 fi
2068 shift
2069
2070 if [[ ! $SL_INFO_DIR ]]; then
2071 echo error: missing '$SL_INFO_DIR' env var >&2
2072 return 1
2073 fi
2074
2075 dorsync=false
2076 haveinfo=false
2077 tmpa=($SL_INFO_DIR/???????????"$remote")
2078 sshinfo=${tmpa[0]}
2079 if [[ -e $sshinfo ]]; then
2080 if $force_rsync; then
2081 rm -f $sshinfo
2082 else
2083 haveinfo=true
2084 fi
2085 fi
2086 if $haveinfo; then
2087 tmp=${sshinfo[0]##*/}
2088 tmp2=${tmp::11}
2089 type=${tmp2: -1}
2090 extra_info=$(cat $sshinfo)
2091 else
2092 # we test for string to know ssh succeeded
2093 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
2094 testcmd="if $testbool; then printf y; else printf n; fi"
2095 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
2096 echo failed sl test. doing plain ssh -v
2097 command ssh -v "${args[@]}" "$remote"
2098 fi
2099 if [[ $tmp == y* ]]; then
2100 type=a
2101 else
2102 dorsync=true
2103 type=b
2104 fi
2105 extra_info="${tmp:1}"
2106 fi
2107 if [[ $sl_test_hook ]]; then
2108 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
2109 fi
2110
2111 if $haveinfo && [[ $type == b ]]; then
2112 info_sec=${tmp::10}
2113 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
2114 files_sec=${files_sec%%.*}
2115 if (( files_sec > info_sec )); then
2116 dorsync=true
2117 rm -f $sshinfo
2118 fi
2119 fi
2120
2121 sync_dirname=${SL_FILES_DIR##*/}
2122
2123 if [[ ! $SL_FILES_DIR ]]; then
2124 echo error: missing '$SL_FILES_DIR' env var >&2
2125 return 1
2126 fi
2127
2128 if $dorsync; then
2129 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
2130 fi
2131 if $dorsync || ! $haveinfo; then
2132 sshinfo=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
2133 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
2134 printf "%s\n" "$extra_info" >$sshinfo
2135 chmod 666 $sshinfo
2136 fi
2137 if [[ $type == b ]]; then
2138 if (( ${#@} )); then
2139 # Theres a couple ways to pass arguments, im not sure whats best,
2140 # but relying on bash 4.4+ escape quoting seems most reliable.
2141 command ssh "${args[@]}" "$remote" \
2142 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
2143 elif [[ ! -t 0 ]]; then
2144 # This case is when commands are being piped to ssh.
2145 # Normally, no bashrc gets sourced.
2146 # But, since we are doing all this, lets source it because we can.
2147 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
2148 else
2149 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
2150 fi
2151 else
2152 if [[ -t 0 ]]; then
2153 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
2154 else
2155 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
2156 fi
2157 fi
2158 # this function inspired from https://github.com/Russell91/sshrc
2159 }
2160
2161 slr() {
2162 sl --rsync "$@"
2163 }
2164 sss() { # ssh solo
2165 sl -oControlMaster=no -oControlPath=/ "$@"
2166 }
2167 # kill off old shared socket then ssh
2168 ssk() {
2169 m ssh -O exit "$@" || [[ $? == 255 ]]
2170 m sl "$@"
2171 }
2172 ccomp ssh sl slr sss ssk
2173 # plain ssh
2174 ssh() {
2175 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
2176 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
2177 else
2178 LC_USEBASHRC=t command ssh "$@"
2179 fi
2180 }
2181
2182
2183 slog() {
2184 # log with script. timing is $1.t and script is $1.s
2185 # -l to save to ~/typescripts/
2186 # -t to add a timestamp to the filenames
2187 local logdir do_stamp arg_base
2188 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
2189 logdir="/a/dt/"
2190 do_stamp=false
2191 while getopts "lt" option
2192 do
2193 case $option in
2194 l ) arg_base=$logdir ;;
2195 t ) do_stamp=true ;;
2196 esac
2197 done
2198 shift $((OPTIND - 1))
2199 arg_base+=$1
2200 [[ -e $logdir ]] || mkdir -p $logdir
2201 $do_stamp && arg_base+=$(date +%F.%T%z)
2202 script -t $arg_base.s 2> $arg_base.t
2203 }
2204 splay() { # script replay
2205 #logRoot="$HOME/typescripts/"
2206 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2207 scriptreplay "$1.t" "$1.s"
2208 }
2209
2210 sr() {
2211 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2212 if [[ $# == 0 ]]; then
2213 sudo -E bash -c -l "$(history -p '!!')"
2214 else
2215 echo this command redos last history item. no argument is accepted
2216 fi
2217 }
2218
2219 srm () {
2220 # with -ll, less secure but faster.
2221 command srm -ll "$@"
2222 }
2223
2224 srun() {
2225 scp $2 $1:/tmp
2226 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
2227 }
2228
2229
2230 swap() {
2231 local tmp
2232 tmp=$(mktemp)
2233 mv $1 $tmp
2234 mv $2 $1
2235 mv $tmp $2
2236 }
2237
2238 tclock() { # terminal clock
2239 local x
2240 clear
2241 date +%l:%_M
2242 len=60
2243 # this goes to full width
2244 #len=${1:-$((COLUMNS -7))}
2245 x=1
2246 while true; do
2247 if (( x == len )); then
2248 end=true
2249 d="$(date +%l:%_M) "
2250 else
2251 end=false
2252 d=$(date +%l:%M:%_S)
2253 fi
2254 echo -en "\r"
2255 echo -n "$d"
2256 for ((i=0; i<x; i++)); do
2257 if (( i % 6 )); then
2258 echo -n _
2259 else
2260 echo -n .
2261 fi
2262 done
2263 if $end; then
2264 echo
2265 x=1
2266 else
2267 x=$((x+1))
2268 fi
2269 sleep 5
2270 done
2271 }
2272
2273
2274 te() {
2275 # test existence / exists
2276 local ret=0
2277 for x in "$@"; do
2278 [[ -e "$x" || -L "$x" ]] || ret=1
2279 done
2280 return $ret
2281 }
2282
2283 psoff() {
2284 # normally, i would just execute these commands in the function.
2285 # however, DEBUG is not inherited, so we need to run it outside a function.
2286 # And we want to run set -x afterwards to avoid spam, so we cram everything
2287 # in here, and then it will run after this function is done.
2288 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
2289 }
2290 pson() {
2291 PROMPT_COMMAND=prompt-command
2292 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2293 trap 'settitle "$BASH_COMMAND"' DEBUG
2294 fi
2295 }
2296
2297 tx() { # toggle set -x, and the prompt so it doesnt spam
2298 if [[ $- == *x* ]]; then
2299 set +x
2300 pson
2301 else
2302 psoff
2303 fi
2304 }
2305
2306 psnetns() {
2307 # show all processes in the network namespace $1.
2308 # blank entries appear to be subprocesses/threads
2309 local x netns
2310 netns=$1
2311 ps -w | head -n 1
2312 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
2313 while read -r l; do
2314 x=$(ps -w --no-headers -p $l);
2315 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2316 done
2317 }
2318 nonet() {
2319 if ! s ip netns list | grep -Fx nonet &>/dev/null; then
2320 s ip netns add nonet
2321 fi
2322 sudo -E env /sbin/ip netns exec nonet sudo -E -u iank /bin/bash
2323 }
2324
2325 m() { printf "%s\n" "$*"; "$@"; }
2326
2327 # update file. note: duplicated in mail-setup
2328 u() {
2329 local tmp tmpdir dest="$1"
2330 local base="${dest##*/}"
2331 local dir="${dest%/*}"
2332 if [[ $dir != "$base" ]]; then
2333 # dest has a directory component
2334 mkdir -p "$dir"
2335 fi
2336 ur=false # u result
2337 tmpdir=$(mktemp -d)
2338 cat >$tmpdir/"$base"
2339 tmp=$(rsync -ic $tmpdir/"$base" "$dest")
2340 if [[ $tmp ]]; then
2341 printf "%s\n" "$tmp"
2342 ur=true
2343 if [[ $dest == /etc/systemd/system/* ]]; then
2344 reload=true
2345 fi
2346 fi
2347 rm -rf $tmpdir
2348 }
2349
2350
2351 uptime() {
2352 if type -p uprecords &>/dev/null; then
2353 uprecords -B
2354 else
2355 command uptime
2356 fi
2357 }
2358
2359 virshrm() {
2360 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
2361 }
2362
2363 vm-set-listen(){
2364 local t
2365 t=$(mktemp)
2366 local vm=$1
2367 local ip=$2
2368 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2369 sed -r "s/listen='[^']+/listen='$ip/"> $t
2370 sudo virsh undefine $vm
2371 sudo virsh define $t
2372 }
2373
2374
2375 vmshare() {
2376 vm-set-listen $1 0.0.0.0
2377 }
2378
2379
2380 vmunshare() {
2381 vm-set-listen $1 127.0.0.1
2382 }
2383
2384 myiwscan() {
2385 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2386 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2387 sudo iw dev wls1 scan | sed -rn "
2388 s/^\Wcapability: (.*)/\1/;Ta;h;b
2389 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2390 # padded to min width of 20
2391 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2392 "|sort -r
2393 }
2394
2395 # Run script by copying it to a temporary location first,
2396 # and changing directory, so we don't have any open
2397 # directories or files that could cause problems when
2398 # remounting.
2399 zr() {
2400 local tmp
2401 tmp=$(type -p "$1")
2402 if [[ $tmp ]]; then
2403 cd $(mktemp -d)
2404 cp -a "$tmp" .
2405 shift
2406 ./"${tmp##*/}" "$@"
2407 else
2408 "$@"
2409 fi
2410 }
2411
2412
2413 # * spark
2414 # spark 1 5 22 13 53
2415 # # => ▁▁▃▂▇
2416
2417 # The MIT License
2418 # Copyright (c) Zach Holman, https://zachholman.com
2419 # https://github.com/holman/spark
2420
2421 # As of 2022-10-28, I reviewed github forks that had several newer
2422 # commits, none had anything interesting. I did a little refactoring
2423 # mostly to fix emacs indent bug.
2424
2425 # Generates sparklines.
2426 _spark_echo()
2427 {
2428 if [ "X$1" = "X-n" ]; then
2429 shift
2430 printf "%s" "$*"
2431 else
2432 printf "%s\n" "$*"
2433 fi
2434 }
2435
2436
2437 spark()
2438 {
2439 local f tc
2440 local n numbers=
2441
2442 # find min/max values
2443 local min=0xffffffff max=0
2444
2445 for n in ${@//,/ }
2446 do
2447 # on Linux (or with bash4) we could use `printf %.0f $n` here to
2448 # round the number but that doesn't work on OS X (bash3) nor does
2449 # `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off
2450 n=${n%.*}
2451 (( n < min )) && min=$n
2452 (( n > max )) && max=$n
2453 numbers=$numbers${numbers:+ }$n
2454 done
2455
2456 # print ticks
2457 local ticks=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █)
2458
2459 # use a high tick if data is constant
2460 (( min == max )) && ticks=(▅ ▆)
2461
2462 tc=${#ticks[@]}
2463 f=$(( ( (max-min) <<8)/( tc - 1) ))
2464 (( f < 1 )) && f=1
2465
2466 for n in $numbers
2467 do
2468 _spark_echo -n ${ticks[$(( ((($n-$min)<<8)/$f) ))]}
2469 done
2470 _spark_echo
2471 }
2472
2473
2474 # * misc stuff
2475
2476
2477 if $use_color && type -p tput &>/dev/null; then
2478 term_bold="$(tput bold)"
2479 term_red="$(tput setaf 1)"
2480 term_green="$(tput setaf 2)"
2481 term_yellow="$(tput setaf 3)"
2482 term_purple="$(tput setaf 5)"
2483 term_nocolor="$(tput sgr0)" # no font attributes
2484
2485 # unused so far. commented for shellcheck
2486 # term_underl="$(tput smul)"
2487 # term_blue="$(tput setaf 4)"
2488 # term_cyan="$(tput setaf 6)"
2489 fi
2490 # Try to keep environment pollution down, EPA loves us.
2491 unset safe_term match_lhs use_color
2492
2493 # * prompt
2494
2495
2496 if [[ $- == *i* ]]; then
2497
2498
2499 case $HOSTNAME in
2500 bk|je|li)
2501 if [[ $EUID == 1000 ]]; then
2502 system-status _ ||:
2503 fi
2504 ;;
2505 esac
2506
2507
2508 # this needs to come before next ps1 stuff
2509 # this stuff needs bash 4, feb 2009,
2510 # old enough to no longer condition on $BASH_VERSION anymore
2511 shopt -s autocd
2512 shopt -s dirspell
2513 PS1='\w'
2514 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2515 PROMPT_DIRTRIM=2
2516 bind -m vi-command B:shell-backward-word
2517 bind -m vi-command W:shell-forward-word
2518 fi
2519
2520 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2521 unset PROMPT_DIRTRIM
2522 PS1="\h:$PS1"
2523 fi
2524
2525 # emacs terminal has problems if this runs slowly,
2526 # so I've thrown a bunch of things at the wall to speed it up.
2527 prompt-command() {
2528 local return=$? # this MUST COME FIRST
2529 local ps_char ps_color
2530 unset IFS
2531
2532 if [[ $HISTFILE ]]; then
2533 history -a # save history
2534 fi
2535
2536 case $return in
2537 0) ps_color="$term_purple"
2538 ps_char='\$'
2539 ;;
2540 *) ps_color="$term_green"
2541 ps_char="$return \\$"
2542 ;;
2543 esac
2544 if [[ ! -O . ]]; then # not owner
2545 if [[ -w . ]]; then # writable
2546 ps_color="$term_bold$term_red"
2547 else
2548 ps_color="$term_bold$term_green"
2549 fi
2550 fi
2551
2552 # faster than sourceing the file im guessing
2553 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2554 eval $(< /dev/shm/iank-status)
2555 fi
2556 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2557 ps_char="@ $ps_char"
2558 fi
2559 # We could test if sudo is active with sudo -nv
2560 # but then we get an email and log of lots of failed sudo commands.
2561 # We could turn those off, but seems better not to.
2562 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2563 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2564 fi
2565 if [[ ! $HISTFILE ]]; then
2566 ps_char="NOHIST $ps_char"
2567 fi
2568 PS1="${PS1%"${PS1#*[wW]}"} $psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2569
2570 # set titlebar. instead, using more advanced
2571 # titelbar below
2572 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2573 }
2574 PROMPT_COMMAND=prompt-command
2575
2576 if [[ $TERM == screen* ]]; then
2577 _title_escape="\033]..2;"
2578 else
2579 # somme sites recommend this, i dunno what the diff is.
2580 #_title_escape="\033]30;"
2581 _title_escape="\033]0;"
2582 fi
2583
2584 # make the titlebar be the last command and the current directory.
2585 settitle () {
2586
2587
2588 # These are some checks to help ensure we dont set the title at
2589 # times that the debug trap is running other than the case we
2590 # want. Some of them might not be needed.
2591 if (( ${#FUNCNAME[@]} != 1 || ${#BASH_ARGC[@]} != 2 || $BASH_SUBSHELL != 0 )); then
2592 return 0
2593 fi
2594 if [[ $1 == prompt-command ]]; then
2595 return 0
2596 fi
2597 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2598 printf "%s" "$*"
2599 echo -ne "\007"
2600 }
2601
2602 # note, this wont work:
2603 # x=$(mktemp); cp a $x
2604 # I havnt figured out why, bigger fish to fry.
2605 #
2606 # for titlebar.
2607 # condition from the screen man page i think.
2608 # note: duplicated in tx()
2609 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2610 trap 'settitle "$BASH_COMMAND"' DEBUG
2611 else
2612 trap DEBUG
2613 fi
2614
2615 fi
2616
2617 # * stuff that makes sense to be at the end
2618
2619
2620 # best practice
2621 unset IFS
2622
2623 # shellcheck disable=SC1090
2624 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2625
2626 # I had this idea to start a bash shell which would run an initial
2627 # command passed through this env variable, then continue on
2628 # interactively. But the use case I had in mind went away.
2629 #
2630 # if [[ $MY_INIT_CMD ]]; then
2631 # "${MY_INIT_CMD[@]}"
2632 # unset MY_INIT_CMD
2633 # fi
2634
2635 # ensure no bad programs appending to this file will have an affect
2636 return 0