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