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