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