7c89382ca6906cf5712fd360bd08b9511cd619c0
[distro-setup] / brc
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4 # this gets sourced. shebang is just for file mode detection
5
6 # Use source ~/.bashrc instead of doing bash -l when running a script
7 # so this can set extdebug and avoid the bash debugger.
8 if [[ -s /a/bin/errhandle/err ]]; then
9 source /a/bin/errhandle/err
10 elif [[ -s $bashrc_dir/err ]]; then
11 # shellcheck source=/a/bin/errhandle/err
12 source $bashrc_dir/err
13 fi
14
15 # In t8, it runs clear_console for login shells by default. I don't want
16 # my console cleared. And linux ttys get cleared without this.
17 if shopt login_shell >/dev/null && [[ -e ~/.bash_logout ]]; then
18 rm ~/.bash_logout
19 fi
20
21 # if [[ -s /usr/share/bash-completion/completions/git ]]; then
22 # source /usr/share/bash-completion/completions/git
23 # fi
24 # if [[ -s /usr/share/bash-completion/completions/gitk ]]; then
25 # source /usr/share/bash-completion/completions/gitk
26 # fi
27
28 # for testing error catching:
29 # t2() {
30 # echo t2
31 # grep sdf sdfd
32 # echo wtf
33 # }
34 # t1() {
35 # echo t1
36 # t2 a b c
37 # }
38
39 # * settings
40
41 CDPATH=.
42
43
44 # remove all aliases. aliases provided by the system tend to get in the way,
45 # for example, error happens if I try to define a function the same name as an alias
46 unalias -a
47
48 # remove gnome keyring warning messages
49 # there is probably a more proper way, but I didnt find any easily on google
50 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
51 #unset GNOME_KEYRING_CONTROL
52
53 # use extra globing features.
54 shopt -s extglob
55 # include .files when globbing, but ignore files name . and ..
56 # setting this also sets dotglob.
57 export GLOBIGNORE="*/.:*/.."
58
59 # Useful info. see man bash.
60 PS4='$LINENO+ '
61
62
63 # broken with bash_completion package. Saw a bug for this once. dont anymore.
64 # still broken in wheezy
65 # still buggered in latest stable from the web, version 2.1
66 # perhaps its fixed in newer git version, which fails to make for me
67 # this note is from 6-2014.
68 # still broken in flidas.
69 #shopt -s nullglob
70
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
73
74 # fix spelling errors for cd, only in interactive shell
75 shopt -s cdspell
76 # append history instead of overwritting it
77 shopt -s histappend
78 # for compatibility, per gentoo/debian bashrc
79 shopt -s checkwinsize
80 # attempt to save multiline single commands as single history entries.
81 shopt -s cmdhist
82 # enable **
83 shopt -s globstar
84
85
86 # inside emacs fixes
87 if [[ $LC_INSIDE_EMACS ]]; then
88 # EMACS is used by bash on startup, but we dont need it anymore.
89 # plus I hit a bug in a makefile which inherited it
90 unset EMACS
91 export LC_INSIDE_EMACS
92 export PAGER=cat
93 export MANPAGER=cat
94 # scp completion does not work, but this doesnt fix it. todo, figure this out
95 #complete -r scp &> /dev/null
96 # todo, remote file completion fails, figure out how to turn it off
97 export NODE_DISABLE_COLORS=1
98 # This gets rid of ugly terminal escape chars in node repl
99 # sometime, Id like to have completion working in emacs shell for node
100 # the offending chars can be found in lib/readline.js,
101 # things that do like:
102 # stream.write('\x1b[' + (x + 1) + 'G');
103 # We can remove them and keep readline, for example by doing this
104 # to start a repl:
105 #!/usr/bin/env nodejs
106 # var readline = require('readline');
107 # readline.cursorTo = function(a,b,c) {};
108 # readline.clearScreenDown = function(a) {};
109 # const repl = require('repl');
110 # var replServer = repl.start('');
111 #
112 # no prompt, or else readline complete seems to be confused, based
113 # on our column being different? node probably needs to send
114 # different kind of escape sequence that is not ugly. Anyways,
115 # completion doesnt work yet even with the ugly prompt, so whatever
116 #
117 export NODE_NO_READLINE=1
118
119 fi
120
121 export SSH_CONFIG_FILE_OVERRIDE=/root/.ssh/confighome
122
123 # emacs has a different default search path than the info command. This
124 # adds the info defaults to emacs, but not the reverse, because I dun
125 # care much about the cli. The search path is only on the cli if you run
126 # "info xxx", or in emacs if you run '(info xxx)', so not that
127 # important, but might as well fix it.
128
129 # info info says this path is what was compiled, and its not documented
130 # anywhere. Through source grepping, i found it in filesys.h of the info
131 # source in trisquel flidas.
132 #
133 # Traling : means for emacs to add its own stuff on to the end.
134
135 export INFOPATH=$PATH:/usr/local/info:/usr/info:/usr/local/lib/info:/usr/lib/info:/usr/local/gnu/info:/usr/local/gnu/lib/info:/usr/gnu/info:/usr/gnu/lib/info:/opt/gnu/info:/usr/share/info:/usr/share/lib/info:/usr/local/share/info:/usr/local/share/lib/info:/usr/gnu/lib/emacs/info:/usr/local/gnu/lib/emacs/info:/usr/local/lib/emacs/info:/usr/local/emacs/info:.:
136
137 # for openwrt system that has no stty, this is easier than
138 # guarding every time i use it.
139 if ! type -p stty >/dev/null; then
140 stty() { :; }
141 fi
142
143
144 if [[ $- == *i* ]]; then
145 # for readline-complete.el
146 if [[ $LC_INSIDE_EMACS ]]; then
147 # all for readline-complete.el
148 stty echo
149 bind 'set horizontal-scroll-mode on'
150 bind 'set print-completions-horizontally on'
151 bind '"\C-i": self-insert'
152 else
153
154 if [[ $KONSOLE_PROFILE_NAME ]]; then
155 TERM=xterm-256color
156 fi
157
158 if [[ $TERM == alacritty && ! -e /usr/share/terminfo/a/alacritty ]]; then
159 # todo: we should try installing the alacritty terminfo if it is not found
160 # https://github.com/alacritty/alacritty/issues/2838
161 TERM=xterm-256color
162 fi
163
164
165 # todo: not sure this works in sakura
166 #stty werase undef
167 #bind "\C-w": kill-region
168 # sakura == xterm-256color
169 # konsole == xterm
170 if [[ $TERM == xterm* ]]; then
171 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
172 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
173 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
174 else
175 # make ctrl-backspace work. for konsole, i fixed it through
176 # /home/iank/.local/share/konsole/default.keytab
177 stty werase '^h'
178 bind '"\eOc": shell-forward-word'
179 bind '"\eOd": shell-backward-word'
180 fi
181 # i cant remember why i did this, probably to free up some keys to bind
182 # to other things in bash.
183 # other than C-c and C-z, the rest defined by stty -a are, at least in
184 # gnome-terminal, overridden by bash, or disabled by the system
185 stty lnext undef stop undef start undef
186 fi
187
188 fi
189
190 export BC_LINE_LENGTH=0
191
192 # ansible option
193 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
194
195 # note, if I use a machine I dont want files readable by all users, set
196 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
197
198 # i for insensitive. the rest from
199 # X means dont remove the current screenworth of output upon exit
200 # R means to show colors n things
201 export LESS=RXij12
202 export SYSTEMD_LESS=$LESS
203
204 export NNN_COLORS=2136
205
206 export SL_FILES_DIR=/b/ds/sl/.iank
207 export SL_INFO_DIR=/p/sshinfo
208
209
210 # * include files
211
212 if [[ -s $bashrc_dir/path-add-function ]]; then
213 source $bashrc_dir/path-add-function
214 if [[ $SSH_CLIENT ]]; then
215 # [[ -d /home/iank/.iank/e/e ]] mounts it unnecessarily, so use this.
216 if grep -qF /home/iank/.iank/e/e /etc/auto.iank /etc/exports &>/dev/null; then
217 export EMACSDIR=/home/iank/.iank/e/e
218 fi
219 fi
220 fi
221
222 # if someone exported $SOE (stop on error), catch errors.
223 #
224 # Note, on debian this results in the following warning when in ssh,
225 # hich I haven't figured out how to fix. It doesn't happen if we source
226 # after the shell has started
227 #
228 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
229 # bash: warning: cannot start debugger; debugging mode disabled
230 if [[ $SOE ]]; then
231 if [[ -e /a/bin/errhandle/err ]]; then
232 source /a/bin/errhandle/err
233 fi
234 fi
235
236 # based on readme.debian. dunno if this will break on other distros.
237 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
238 source /usr/share/wcd/wcd-include.sh
239 fi
240
241 if [[ -s /a/bin/small-misc-bash/ll-function ]]; then
242 source /a/bin/small-misc-bash/ll-function
243 elif [[ -s $bashrc_dir/ll-function ]]; then
244 # shellcheck source=/a/bin/small-misc-bash/ll-function
245 source $bashrc_dir/ll-function
246 fi
247
248
249
250
251 # * functions
252 ccomp() { # copy completion
253 local src=$1
254 local c
255 shift
256 if ! c=$(complete -p $src 2>/dev/null); then
257 _completion_loader $src &>/dev/null ||:
258 c=$(complete -p $src 2>/dev/null) || return 0
259 fi
260 # remove $src( .*|$)
261 c=${c% $src}
262 c=${c%% $src *}
263 eval $c $*
264 }
265
266
267 ..() { c ..; }
268 ...() { c ../..; }
269 ....() { c ../../..; }
270 .....() { c ../../../..; }
271 ......() { c ../../../../..; }
272
273 chere() {
274 local f path
275 for f; do
276 path=$(readlink -e "$f")
277 echo "cat >$path <<'EOF'"
278 cat "$f"
279 echo EOF
280 done
281 }
282
283
284 # file cut copy and paste, like the text buffers :)
285 # I havnt tested these.
286 _fbufferinit() { # internal use
287 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
288 rm -rf "${my_f_tempdir:?}"/*
289 }
290 fcp() { # file cp
291 _fbufferinit
292 cp "$@" "$my_f_tempdir"/
293 }
294 fct() { # file cut
295 _fbufferinit
296 mv "$@" "$my_f_tempdir"/
297 }
298 fpst() { # file paste
299 [[ $2 ]] && { echo too many arguments; return 1; }
300 target=${1:-.}
301 cp "$my_f_tempdir"/* "$target"
302 }
303
304 _khfix_common() {
305 local host ip port
306 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" || [[ $? == 124 ]])
307 if [[ ! $ip ]]; then
308 echo "khfix: ssh failed"
309 return 1
310 fi
311 if [[ $port != 22 ]]; then
312 ip_entry="[$ip]:$port"
313 host_entry="[$host]:$port"
314 else
315 ip_entry=$ip
316 host_entry=$host
317 fi
318 if [[ $host != $ip ]]; then
319 ssh-keygen -R "$host_entry" -f $(readlink -f ~/.ssh/known_hosts)
320 fi
321 echo "khfix: removing key for $ip_entry"
322 ssh-keygen -R "$ip_entry" -f $(readlink -f ~/.ssh/known_hosts)
323 rootsshsync
324 }
325 khfix() { # known hosts fix
326 _khfix_common "$@" || return 1
327 ssh $1 :
328 }
329 khcopy() {
330 _khfix_common "$@"
331 ssh-copy-id $1
332 }
333
334 a() {
335 local x
336 x=$(readlink -nf "${1:-$PWD}")
337 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
338 echo -n "$x" | xclip -selection clipboard
339 echo -n "$x" | xclip
340 }
341
342 # a1 = awk {print $1}
343 for field in {1..20}; do
344 eval a$field"() { awk '{print \$$field}'; }"
345 done
346 # h1 = head -n1
347 for num in {1..9}; do
348 eval h$num"() { head -n$num; }"
349 done
350
351
352 b() {
353 # backwards
354 c -
355 }
356
357
358 # c. better cd
359 if type -p wcd &>/dev/null; then
360 if [[ $LC_INSIDE_EMACS ]]; then
361 c() { wcd -c -z 50 -o "$@"; }
362 else
363 # lets see what the fancy terminal does from time to time
364 c() { wcd -c -z 50 "$@"; }
365 fi
366 else
367 c() { cd "$@"; }
368 fi
369 ccomp cd c
370
371 c4() { c /var/log/exim4; }
372
373 caa() { git commit --amend --no-edit -a; }
374
375 cf() {
376 for f; do
377 hr
378 echo "$f"
379 hr
380 cat "$f"
381 done
382 }
383 caf() {
384 # shellcheck disable=SC2033
385 find -L "$@" -type f -not \( -name .svn -prune -o -name .git -prune \
386 -o -name .hg -prune -o -name .editor-backups -prune \
387 -o -name .undo-tree-history -prune \) \
388 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
389
390 }
391 ccomp cat cf caf
392
393 calc() { echo "scale=3; $*" | bc -l; }
394 # no having to type quotes, but also no command history:
395 clc() {
396 local x
397 read -r x
398 echo "scale=3; $x" | bc -l
399 }
400
401 cam() {
402 git commit -am "$*"
403 }
404
405 ccat () { # config cat. see a config without extra lines.
406 grep '^\s*[^;[:space:]#]' "$@" || [[ $? == 1 ]]
407 }
408 ccomp grep ccat
409
410 chrbind() {
411 local d
412 # dev/pts needed for pacman signature check
413 for d in dev proc sys dev/pts; do
414 [[ -d $d ]]
415 if ! mountpoint $d &>/dev/null; then
416 s mount -o bind /$d $d
417 fi
418 done
419 }
420
421
422 _cdiff-prep() {
423 # join options which are continued to multiples lines onto one line
424 local first=true
425 while IFS= read -r line; do
426 # remove leading spaces/tabs. assumes extglob
427 if [[ $line == "[ ]*" ]]; then
428 line="${line##+( )}"
429 fi
430 if $first; then
431 pastline="$line"
432 first=false
433 elif [[ $line == *=* ]]; then
434 echo "$pastline" >> "$2"
435 pastline="$line"
436 else
437 pastline="$pastline $line"
438 fi
439 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
440 echo "$pastline" >> "$2"
441 }
442
443 cdiff() {
444 # diff config files,
445 # setup for format of postfix, eg:
446 # option = stuff[,]
447 # [more stuff]
448 local pastline unified f1 f2
449 unified="$(mktemp)"
450 f1="$(mktemp)"
451 f2="$(mktemp)"
452 _cdiff-prep "$1" "$f1"
453 _cdiff-prep "$2" "$f2"
454 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
455 while IFS= read -r line; do
456 # the default bright red / blue doesnt work in emacs shell
457 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
458 done < "$unified"
459 }
460
461
462 cat-new-files() {
463 local start=$SECONDS
464 local dir="$1"
465 inotifywait -m "$dir" -e create -e moved_to |
466 # shellcheck disable=SC2030
467 while read -r filedir _ file; do
468 cat "$filedir$file"
469 hr
470 calc $((SECONDS - start)) / 60
471 sleep 5
472 done
473
474 }
475
476 # shellcheck disable=SC2032
477 chown() {
478 # makes it so chown -R symlink affects the symlink and its target.
479 if [[ $1 == -R ]]; then
480 shift
481 command chown -h "$@"
482 command chown -R "$@"
483 else
484 command chown "$@"
485 fi
486 }
487
488 cim() {
489 git commit -m "$*"
490 }
491
492 cl() {
493 # choose recent directory. cl = cd list
494 c =
495 }
496
497 d() { builtin bg "$@"; }
498 ccomp bg d
499
500 dc() {
501 diff --strip-trailing-cr -w "$@" # diff content
502 }
503 ccomp diff dc
504
505 despace() {
506 local x y
507 for x in "$@"; do
508 y="${x// /_}"
509 safe_rename "$x" "$y"
510 done
511 }
512
513 dig() {
514 command dig +nostats +nocmd "$@"
515 }
516 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
517 digsort() {
518 local sec
519 sec=
520 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
521 if [[ $l == [^\;]* ]]; then
522 sec+="$l"$'\n'
523 else
524 if [[ $sec ]]; then
525 printf "%s" "$sec" | sort
526 sec=
527 fi
528 printf "%s\n" "$l"
529 fi
530 done
531 }
532 ccomp dig digsort
533 # compare digs to the 2 servers
534 # usage: digdiff @server1 @server2 DIG_ARGS
535 # note: only the soa master nameserver will respond with
536 # ra "recursive answer" flag. That difference is meaningless afaik.
537 digdiff() {
538 local s1 s2
539 s1=$1
540 shift
541 s2=$1
542 shift
543 digsort $s1 "$@" | tee /tmp/digdiff
544 diff -u /tmp/digdiff <(digsort $s2 "$@")
545 }
546
547 dt() {
548 date "+%A, %B %d, %r" "$@"
549 }
550 ccomp date dt
551
552 dus() { # du, sorted, default arg of
553 du -sh ${@:-*} | sort -h
554 }
555 ccomp du dus
556
557
558 e() { echo "$@"; }
559
560 # echo args
561 ea() {
562 if (( ! $# )); then
563 echo no args
564 fi
565 for arg; do
566 printf "%qEOL\n" "${arg}"
567 printf "%s" "${arg}" |& hexdump -C
568 done
569 }
570 # echo vars. print var including escapes, etc
571 ev() {
572 if (( ! $# )); then
573 echo no args
574 fi
575 for arg; do
576 printf "%qEOL\n" "${!arg}"
577 printf "%s" "${!arg}" |& hexdump -C
578 done
579 }
580
581 ediff() {
582 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
583 emacs --eval "(ediff-files \"$1\" \"$2\")"
584 }
585
586 # mail related
587 etail() {
588 tail -F /var/log/exim4/mainlog -n 200 "$@"
589 }
590 ccomp tail etail
591
592 # print exim old pids
593 eoldpids() {
594 local configtime pid piduptime now daemonpid
595 printf -v now '%(%s)T' -1
596 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
597 if [[ -s /run/exim4/exim.pid ]]; then
598 daemonpid=$(cat /run/exim4/exim.pid)
599 fi
600 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
601 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
602 if [[ $pid == $daemonpid ]]; then
603 continue
604 fi
605 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
606 if (( configtime > now - piduptime )); then
607 echo $pid
608 fi
609 done
610 }
611
612 # exim tail but only watch lines from new pids
613 etailnew() {
614 local pid oldpids
615 for pid in $(eoldpids); do
616 oldpids+="$pid|"
617 done
618 if [[ $oldpids ]]; then
619 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
620 else
621 etail
622 fi
623 }
624 # exim watch as old pids go away
625 ewatchold() {
626 local configtime pid piduptime now
627 local -i count
628 local -a oldpids
629 count=0
630 while true; do
631 oldpids=($(eoldpids))
632 if (( ! ${#oldpids[@]} )); then
633 return
634 fi
635 # print the date every 20 iterations
636 if (( ! count % 20 )); then
637 date
638 fi
639 count+=1
640 ps -f -p "${oldpids[*]}"
641 sleep 1
642 done
643 }
644
645 eless() {
646 less /var/log/exim4/mainlog
647 }
648 ccomp less eless
649 eqcat() {
650 exiqgrep -i -o 60 | while read -r i; do
651 hlm exim -Mvc $i
652 echo
653 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
654 done
655 }
656 eqrmf() {
657 exiqgrep -i | xargs exim -Mrm
658 }
659
660 econfdevnew() {
661 rm -rf /tmp/edev
662 mkdir -p /tmp/edev/etc
663 cp -ra /etc/exim4 /tmp/edev/etc
664 cp -ra /etc/alias* /tmp/edev/etc
665 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
666 econfdev
667 }
668 econfdev() {
669 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
670 }
671
672
673
674 # shellcheck disable=SC2032
675 f() {
676 # cd forward
677 c +
678 }
679
680 fa() {
681 # find array. make an array of file names found by find into $x
682 # argument: find arguments
683 # return: find results in an array $x
684 while read -rd ''; do
685 x+=("$REPLY");
686 done < <(find "$@" -print0);
687 }
688
689 faf() { # find all files. use -L to follow symlinks
690 find "$@" -not \( -name .svn -prune -o -name .git -prune \
691 -o -name .hg -prune -o -name .editor-backups -prune \
692 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
693 }
694
695 # mail related
696 frozen() {
697 rm -rf /tmp/frozen
698 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
699 sudo exim -Mvl $id
700 echo
701 sudo exim -Mvh $id
702 echo
703 sudo exim -Mvb $id
704 echo -e '\n\n##############################\n'
705 done | tee -a /tmp/frozen
706 }
707 frozenrm() {
708 local ids=()
709 while read -r line; do
710 printf '%s\n' "$line"
711 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
712 done < <(s mailq)
713 echo "sleeping for 2 in case you change your mind"
714 sleep 2
715 sudo exim -Mrm "${ids[@]}"
716 }
717
718 funce() {
719 # like -e for functions. returns on error.
720 # at the end of the function, disable with:
721 # trap ERR
722 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
723 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
724 trap ERR
725 return' ERR
726 }
727
728 getdir () {
729 local help="Usage: getdir [--help] PATH
730 Output the directory of PATH, or just PATH if it is a directory."
731 if [[ $1 == --help ]]; then
732 echo "$help"
733 return 0
734 fi
735 if [[ $# -ne 1 ]]; then
736 echo "getdir error: expected 1 argument, got $#"
737 return 1
738 fi
739 if [[ -d $1 ]]; then
740 echo "$1"
741 else
742 local dir
743 dir="$(dirname "$1")"
744 if [[ -d $dir ]]; then
745 echo "$dir"
746 else
747 echo "getdir error: directory does not exist"
748 return 1
749 fi
750 fi
751 }
752
753 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
754 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
755 local root
756 root=$(gitroot) || return 1 # function to set gitroot
757 builtin cd "$root"
758 git symbolic-ref HEAD refs/heads/$1
759 rm .git/index
760 git clean -fdx
761 }
762
763 # shellcheck disable=SC2120
764 gitroot() {
765 local help="Usage: gitroot [--help]
766 Print the full path to the root of the current git repo
767
768 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
769 and works in older versions of git which did not have that."
770 if [[ $1 == --help ]]; then
771 echo "$help"
772 return
773 fi
774 local p
775 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
776 [[ $p != /* ]] && p=$PWD
777 echo "${p%%/.git}"
778 }
779
780 g() {
781
782 # todo: patch emacs so it will look elsewhere. this is kinda sad:
783 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
784
785 local args gdb=false
786
787 if [[ $EMACSDIR ]]; then
788 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
789 fi
790
791 if [[ $DISPLAY ]]; then
792 args=-n
793 fi
794
795 if (( $# == 0 )); then
796 args+=" -c"
797 fi
798 # duplicate -c, but oh well
799 if ! pgrep -u $EUID emacsclient; then
800 if (( $# == 0 )) && type -p gdb &>/dev/null; then
801 gdb=true
802 else
803 args+=" -c"
804 fi
805 fi
806 if [[ $EMACSDIR ]]; then
807 # Alter the path here, otherwise the nfs mount gets triggered on the
808 # first path lookup when emacs is not being used.
809 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
810 else
811 if $gdb; then
812 # due to a bug, we cant debug from the start unless we get a new gdb
813 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
814 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
815 m emacsclient -a "" $args "$@"
816 sleep 1
817 cd /a/opt/emacs-$(distro-name)$(distro-num)
818 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
819 cd -
820 else
821 m emacsclient -a "" $args "$@"
822 fi
823 fi
824 }
825
826 # force terminal version
827 gn() {
828 g -n "$@"
829 }
830
831 gmacs() {
832 # quit will prompt if the program crashes.
833 gdb -ex=r -ex=quit --args emacs "$@"; r;
834 }
835
836 gdkill() {
837 # kill the emacs daemon
838 pk1 emacs --daemon
839 }
840
841 gr() {
842 grep -iIP --color=auto "$@" || return $?
843 }
844 grr() { # grep recursive
845 # Don't return 1 on nonmatch because this is meant to be
846 # interactive, not in a conditional.
847 if [[ ${#@} == 1 ]]; then
848 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
849 else
850 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
851 fi
852 }
853 ccomp grep gr grr
854
855 rg() { grr "$@"; }
856 ccomp grep rg
857
858 hr() { # horizontal row. used to break up output
859 printf "$(tput setaf 5 2>/dev/null ||:)â–ˆ$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
860 echo
861 }
862 # highlight
863 hl() {
864 local col input_len=0
865 for arg; do
866 input_len=$((input_len + 1 + ${#arg}))
867 done
868 col=$((60 - input_len))
869 printf "\e[1;97;41m%s" "$*"
870 if (( col > 0 )); then
871 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
872 fi
873 echo
874 }
875 hlm() { hl "$*"; "$@"; }
876
877 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
878
879
880 # get latest hub and run it
881 # main command to use:
882 # hub pull-request --no-edit
883 # --no-edit means to use the first commit\'s message as the pull request message.
884 # If that fails, try doing
885 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
886 # where branch is usually master. it does the pr against your current branch.
887 #
888 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
889 # it\'s at ~/.config/hub
890 hub() {
891 local up uptar updir p
892 p=/github/hub/releases/
893 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
894 uptar=${up##*/}
895 updir=${uptar%.tgz}
896 if [[ ! -e /a/opt/$updir ]]; then
897 rm -rf /a/opt/hub-linux-amd64*
898 wget -P /a/opt $up
899 tar -C /a/opt -zxf /a/opt/$uptar
900 rm -f /a/opt/$uptar
901 fi
902 if ! which hub &>/dev/null; then
903 sudo /a/opt/$updir/install
904 fi
905
906 # save token across computers
907 if [[ ! -L ~/.config/hub ]]; then
908 if [[ -e ~/.config/hub ]]; then
909 mv ~/.config/hub /p/c/subdir_files/.config/
910 fi
911 if [[ -e /p/c/subdir_files/.config/hub ]]; then
912 conflink
913 fi
914 fi
915 command hub "$@"
916 }
917
918 i() { git "$@"; }
919 ccomp git i
920
921 ic() {
922 # fast commit all
923 git commit -am "$*"
924 }
925
926
927 ifn() {
928 # insensitive find
929 find -L . -not \( -name .svn -prune -o -name .git -prune \
930 -o -name .hg -prune -o -name .editor-backups -prune \
931 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
932 }
933
934 ifd() {
935 # insensitive find directory
936 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
937 -o -name .hg -prune -o -name .editor-backups -prune \
938 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
939 }
940
941
942 ipdrop() {
943 sudo iptables -A INPUT -s $1 -j DROP
944 }
945
946
947 istext() {
948 grep -Il "" "$@" &>/dev/null
949 }
950
951 jtail() {
952 journalctl -n 10000 -f "$@"
953 }
954 jr() { journalctl "$@" ; }
955 jrf() { journalctl -f "$@" ; }
956 jru() {
957 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
958 }
959
960 l() {
961 if [[ $PWD == /[iap] ]]; then
962 command ls -A --color=auto -I lost+found "$@"
963 else
964 command ls -A --color=auto "$@"
965 fi
966 }
967
968 lcn() { locate -i "*$**"; }
969
970 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
971
972 lt() { ll -tr "$@"; }
973
974 lld() { ll -d "$@"; }
975
976 ccomp ls l lg lt lld ll
977
978 # low recursively
979 lowr() {
980 local f dirs i a
981 local -a all
982 for dirs in false true; do
983 for f; do
984 if [[ -d $f ]]; then
985 all=("$f"/**)
986 # reverse the order to rename the nested dirs first.
987 # note: 0 element is the dir itself
988 for ((i=${#all[@]}-1; i>=1; i--)); do
989 a="${all[i]}"
990 if $dirs && [[ -d $a ]]; then
991 # e dirs low "$a" # debug
992 low "$a"
993 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
994 # debug
995 # e not dirs low "$a" # debug
996 low "$a"
997 fi
998 done
999 fi
1000 # just rename all the top level args on the second pass
1001 if $dirs; then
1002 # e final dirs low "$f" # debug
1003 low "$f"
1004 fi
1005 done
1006 done
1007 }
1008
1009 low() { # make filenames lowercase, remove bad chars
1010 local arg new dir f
1011 for arg; do
1012 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1013 dir="${arg%/*}"
1014 if (( ${#dir} == ${#arg} )); then
1015 dir=.
1016 fi
1017 f="${arg##*/}"
1018 new="${f,,}" # downcase
1019 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
1020 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1021 new="${new%"${new##*[[:alnum:]]}"}"
1022 # remove bad underscores, like __ and _._
1023 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1024 safe_rename "$dir/$f" "$dir/$new" || return 1
1025 done
1026 return 0
1027 }
1028
1029 lower() { # make first letter of filenames lowercase.
1030 local x
1031 for x in "$@"; do
1032 if [[ ${x::1} == [A-Z] ]]; then
1033 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1034 safe_rename "$x" "$y" || return 1
1035 fi
1036 done
1037 }
1038
1039
1040 k() { # history search
1041 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1042 }
1043 ks() { # history search
1044 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1045 }
1046 ccomp grep k ks
1047
1048
1049 make-targets() {
1050 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1051 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1052 }
1053
1054 mkc() {
1055 mkdir "$1"
1056 c "$1"
1057 }
1058 ccomp mkdir mkc
1059
1060 mkct() {
1061 mkc $(mktemp -d)
1062 }
1063
1064 mkt() { # mkdir and touch file
1065 local path="$1"
1066 mkdir -p "$(dirname "$path")"
1067 touch "$path"
1068 }
1069
1070 # shellcheck disable=SC2032
1071 mkdir() { command mkdir -p "$@"; }
1072
1073 nags() {
1074 # https://github.com/HenriWahl/Nagstamon/issues/357
1075 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1076 /usr/lib/notification-daemon/notification-daemon &
1077 fi
1078 /usr/bin/nagstamon &
1079 }
1080
1081 nmt() {
1082 s nmtui-connect "$@"
1083 }
1084
1085 nopanic() {
1086 # shellcheck disable=SC2024
1087 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1088 }
1089
1090 p8() { ping "$@" 8.8.8.8; }
1091 p6() { ping6 "$@" 2001:4860:4860::8888; }
1092
1093 pkx() { # package extract
1094 local pkg cached tmp f
1095 c $(mktemp -d)
1096 pkg=$1
1097 # shellcheck disable=SC2012
1098 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1099 if [[ $cached ]]; then
1100 cp $cached .
1101 else
1102 aptitude download $pkg || return 1
1103 fi
1104 tmp=(*); f=${tmp[0]} # only 1 expected
1105 ex $f
1106 rm -f $f
1107 }
1108
1109 # pgrep and kill
1110 pk1() {
1111 local pid
1112 pid=($(pgrep -f "$*"))
1113 case ${#pid[@]} in
1114 1)
1115 # shellcheck disable=SC2128
1116 {
1117 ps -F $pid
1118 m kill $pid
1119 }
1120 ;;
1121 0) echo "no pid found" ;;
1122 *)
1123 ps -F ${pid[@]}
1124 ;;
1125 esac
1126 }
1127
1128 psg () {
1129 local x y help
1130 help="Usage: psg [--help] GREP_ARGS
1131 grep ps and output in a nice format"
1132 if [[ $1 == --help ]]; then
1133 echo "$help"
1134 return
1135 fi
1136 x=$(s ps -eF)
1137 # final grep is because some commands tend to have a lot of trailing spaces
1138 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1139 if [[ $y ]]; then
1140 echo "$x" | head -n 1 || [[ $? == 141 ]]
1141 echo "$y"
1142 fi
1143 }
1144
1145 pubip() { curl -4s https://icanhazip.com; }
1146 pubip6() { curl -6s https://icanhazip.com; }
1147 whatismyip() { pubip; }
1148
1149
1150 q() { # start / launch a program in the backround and redir output to null
1151 "$@" &> /dev/null &
1152 }
1153
1154 # shellcheck disable=SC2120
1155 r() {
1156 if [[ $HISTFILE ]]; then
1157 history -a # save history
1158 fi
1159 trap ERR # this avoids a segfault
1160 exit ${1:0}
1161 # i had this redir, not sure why
1162 # exit "$@" 2>/dev/null
1163 }
1164
1165 # scp is insecure and deprecated.
1166 scp() {
1167 rsync --inplace "$@"
1168 }
1169
1170 randport() {
1171 # available high ports are 1024-65535,
1172 # but lets skip things that are more likely to be in use
1173 python3 <<'EOF'
1174 import secrets
1175 print(secrets.SystemRandom().randrange(10002,65500))
1176 EOF
1177 }
1178
1179 # reapply bashrc
1180 reb() {
1181 source ~/.bashrc
1182 }
1183
1184 rl() {
1185 readlink -f "$@"
1186 }
1187 ccomp readlink rl
1188
1189 rsd() {
1190 # rsync, root is required to keep permissions right.
1191 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1192 # --no-times --delete
1193 # basically, make an exact copy, use checksums instead of file times to be more accurate
1194 rsync -ahvic --delete "$@"
1195 }
1196 rsa() {
1197 # like rlu, but dont delete files on the target end which
1198 # do not exist on the original end.
1199 rsync -ahvic "$@"
1200 }
1201 rst() {
1202 # rl without preserving modification time.
1203 rsync -ahvic --delete --no-t "$@"
1204 }
1205 rsu() { # [OPTS] HOST PATH
1206 # eg. rlu -opts frodo /testpath
1207 # relative paths will expanded with readlink -f.
1208 opts=("${@:1:$#-2}") # 1 to last -2
1209 path="${*:$#}" # last
1210 host="${*:$#-1:1}" # last -1
1211 if [[ $path == .* ]]; then
1212 path=$(readlink -f $path)
1213 fi
1214 # rync here uses checksum instead of time so we dont mess with
1215 # unison relying on time as much. g is for group, same reason
1216 # to keep up with unison.
1217 m s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1218 }
1219 ccomp rsync rsd rsa rst rsu
1220
1221 resolvcat() {
1222 local f
1223 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1224 m s nscd -i hosts
1225 fi
1226 f=/etc/resolv.conf
1227 echo $f:; ccat $f
1228 hr; s ss -lpn 'sport = 53'
1229 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1230 # this will fail is dnsmasq is failed
1231 hr; m ser status dnsmasq | cat || :
1232 f=/etc/dnsmasq.conf
1233 hr; echo $f:; ccat $f
1234 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1235 f=/etc/dnsmasq-servers.conf
1236 hr; echo $f:; ccat $f
1237 fi
1238 hr
1239 echo /etc/nsswitch.conf:
1240 grep '^ *hosts:' /etc/nsswitch.conf
1241 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1242 hr; m ser status systemd-resolved | cat || :
1243 hr; m systemd-resolve --status | cat
1244 fi
1245
1246 }
1247 rcat() {
1248 resolvcat | less
1249 }
1250 reresolv() {
1251 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1252 m ser stop nscd
1253 sleep .5
1254 m ser start nscd
1255 m sudo nscd -i hosts
1256 fi
1257 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1258 m sudo systemctl restart dnsmasq
1259 fi
1260 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1261 m sudo systemctl restart systemd-resolved
1262 fi
1263 if type -P resolvectl &>/dev/null; then
1264 resolvectl flush-caches
1265 fi
1266 }
1267
1268 rmstrips() {
1269 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1270 }
1271
1272 s() {
1273 # background
1274 # I use a function because otherwise we cant use in a script,
1275 # cant assign to variable.
1276 #
1277 # note: gksudo is recommended for X apps because it does not set the
1278 # home directory to the same, and thus apps writing to ~ fuck things up
1279 # with root owned files.
1280 #
1281 if [[ $EUID != 0 || $1 == -* ]]; then
1282 # shellcheck disable=SC2034
1283 SUDOD="$PWD" command sudo -i "$@"
1284 DID_SUDO=true
1285 else
1286 "$@"
1287 fi
1288 }
1289 sb() { # sudo bash -c
1290 # use sb instead of s is for sudo redirections,
1291 # eg. sb 'echo "ok fine" > /etc/file'
1292 # shellcheck disable=SC2034
1293 local SUDOD="$PWD"
1294 sudo -i bash -c "$@"
1295 }
1296 ccomp sudo s sb
1297
1298 safe_rename() { # warn and dont rename if file exists.
1299 # mv -n exists, but it\'s silent
1300 if [[ $# != 2 ]]; then
1301 echo safe_rename error: $# args, need 2 >2
1302 return 1
1303 fi
1304 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1305 if [[ -e $2 || -L $2 ]]; then
1306 echo "Cannot rename $1 to $2 as it already exists."
1307 else
1308 mv -vi "$1" "$2"
1309 fi
1310 fi
1311 }
1312
1313
1314
1315 sd() {
1316 sudo dd status=none of="$1"
1317 }
1318
1319 ser() {
1320 if type -p systemctl &>/dev/null; then
1321 s systemctl $1 $2
1322 else
1323 s service $2 $1
1324 fi
1325 }
1326 seru() { systemctl --user "$@"; }
1327 # like restart, but do nothing if its not already started
1328 srestart() {
1329 local service=$1
1330 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1331 systemctl restart $service
1332 fi
1333 }
1334
1335 setini() { # set a value in a .ini style file
1336 key="$1" value="$2" section="$3" file="$4"
1337 if [[ -s $file ]]; then
1338 sed -ri -f - "$file" <<EOF
1339 # remove existing keys
1340 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1341 # add key
1342 /^\s*\[$section\]/a $key=$value
1343 # from section to eof, do nothing
1344 /^\s*\[$section\]/,\$b
1345 # on the last line, if we haven't found section yet, add section and key
1346 \$a [$section]\\
1347 $key=$value
1348 EOF
1349 else
1350 cat >"$file" <<EOF
1351 [$section]
1352 $key=$value
1353 EOF
1354 fi
1355 }
1356
1357 sgo() { # service go
1358 service=$1
1359 ser restart $service || return 1
1360 if type -p systemctl &>/dev/null; then
1361 ser enable $service
1362 fi
1363 }
1364 soff () {
1365 for service; do
1366 # ignore services that dont exist
1367 if systemctl cat $service &>/dev/null; then
1368 ser stop $service;
1369 ser disable $service
1370 fi
1371 done
1372 }
1373
1374 sgu() {
1375 systemctl list-unit-files | rg "$@"
1376 }
1377
1378
1379 sk() {
1380 # 2029: "unescaped, this expands on the client side." yes, I know how ssh works
1381 # 2164: "Use 'cd ... || exit' or 'cd ... || return' in case cd fails." i have automatic error handling
1382 # 2086: unquoted $var
1383 # 2046: unquoted $(cmd)
1384 # 2068: Double quote array expansions to avoid re-splitting elements.
1385 # 2119: Functions with optional args get bad warnings when none are passed.
1386 # 2033: too many false positives for thing that will never work, passing shell function to find.
1387 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1388 shellcheck -x -e 2029,2164,2086,2046,2068,2119,2033 "$@" || return $?
1389 # had this before. not sure what it is 2119
1390 }
1391
1392
1393 # sl: ssh, but firsh rsync our bashrc and related files to a special
1394 # directory on the remote host if needed.
1395
1396 # Some environment variables and files need to be setup for this to work
1397 # (mine are set at the beginning of this file)
1398
1399 # SL_FILES_DIR: Environment variable. Path to folder which should at
1400 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1401 # remote hosts (top level symlinks are resolved) unless the host already
1402 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1403 # control and sync files to separately and already has the ~/.bashrc you
1404 # want. The remote bash will also take its .inputrc config from this
1405 # folder (default of not existing is fine). Mine looks like this:
1406 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1407
1408 # SL_INFO_DIR: Environment variable. This folder stores info about what
1409 # we detected on the remote system and when we last synced. It will be created
1410 # if it does not exist. Sometimes you may want to forget about a
1411 # remote system, you can use sl --rsync, or the function for that slr
1412 # below.
1413
1414 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1415 # depending on the remote host. Run this string on the remote host the
1416 # first time sl is run (or if we run slr). The result is passed to
1417 # SL_TEST_HOOK. For example,
1418 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1419
1420 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1421 # $SL_FILES_DIR to vary the files synced.
1422
1423 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1424 # example to exclude files within a directory. Note, excluded
1425 # files wont be deleted on rsync, you can add --delete-excluded
1426 # to the rsync command if that is desired.
1427
1428 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1429
1430 # For when ~/.bashrc is already customized on the remote server, you
1431 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1432 # commands, even in scripts. This paragraph is all about that. bash
1433 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1434 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1435 # and if you customize it, probably has bugs from time to time. This is
1436 # bad. Here's how I fix it. I have a special condition to "return" in my
1437 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1438 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1439 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1440 # separate file because even if I return early on, the whole file gets
1441 # parsed which can fail if there is a syntax error.
1442 sl() {
1443 # Background on LC_USEBASHRC var (no need to read if you just want to
1444 # use this function): env variables sent across ssh are strictly
1445 # limited, but we get LC_* at least in debian based machines, so we
1446 # just make that * be something no normal program would use. Note, on
1447 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1448 # set, and the inner shell also allows running a nondefault
1449 # .bashrc. This means the outer shell still ran the default .bashrc,
1450 # but that is the best we can do.
1451
1452 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1453 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1454 declare -a args tmpa
1455
1456 args=($SL_SSH_ARGS)
1457
1458 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1459 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1460 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1461 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
1462 # [command]
1463
1464 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
1465 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
1466 # [-F configfile] [-I pkcs11] [-i identity_file]
1467 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
1468 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
1469 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
1470
1471 force_rsync=false
1472 if [[ $1 == --rsync ]]; then
1473 force_rsync=true
1474 shift
1475 fi
1476
1477 sl_test_cmd=$SL_TEST_CMD
1478 sl_test_hook=$SL_TEST_HOOK
1479 sl_rsync_args=$SL_RSYNC_ARGS
1480 while [[ $1 ]]; do
1481 case "$1" in
1482 --rsync)
1483 force_rsync=true
1484 ;;
1485 --sl-test-cmd)
1486 sl_test_cmd="$2"
1487 shift
1488 ;;
1489 --sl-test-hook)
1490 sl_test_hook="$2"
1491 shift
1492 ;;
1493 --sl-rsync-args)
1494 sl_rsync_args="$2"
1495 shift
1496 ;;
1497 *)
1498 break
1499 ;;
1500 esac
1501 shift
1502 done
1503
1504 while [[ $1 ]]; do
1505 case "$1" in
1506 # note we dont support things like -4oOption
1507 -[46AaCfGgKkMNnqsTtVvXxYy]*)
1508 args+=("$1"); shift
1509 ;;
1510 -[bcDEeFIiJLlmOopQRSWw]*)
1511 # -oOption etc is valid
1512 if (( ${#1} >= 3 )); then
1513 args+=("$1"); shift
1514 else
1515 args+=("$1" "$2"); shift 2
1516 fi
1517 ;;
1518 *)
1519 break
1520 ;;
1521 esac
1522 done
1523 remote="$1"
1524 if [[ ! $remote ]]; then
1525 echo $0: error hostname required >&2
1526 return 1
1527 fi
1528 shift
1529
1530 if [[ ! $SL_INFO_DIR ]]; then
1531 echo error: missing '$SL_INFO_DIR' env var >&2
1532 return 1
1533 fi
1534
1535 now=$(date +%s)
1536 dorsync=false
1537 haveinfo=false
1538 tmpa=($SL_INFO_DIR/???????????"$remote")
1539 sshinfo=${tmpa[0]}
1540 if [[ -e $sshinfo ]]; then
1541 if $force_rsync; then
1542 rm -f $sshinfo
1543 else
1544 haveinfo=true
1545 fi
1546 fi
1547 if $haveinfo; then
1548 tmp=${sshinfo[0]##*/}
1549 tmp2=${tmp::11}
1550 type=${tmp2: -1}
1551 extra_info=$(cat $sshinfo)
1552 else
1553 # we test for string to know ssh succeeded
1554 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
1555 testcmd="if $testbool; then printf y; else printf n; fi"
1556 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
1557 echo failed sl test. doing plain ssh -v
1558 command ssh -v "${args[@]}" "$remote"
1559 fi
1560 if [[ $tmp == y* ]]; then
1561 type=a
1562 else
1563 dorsync=true
1564 type=b
1565 fi
1566 extra_info="${tmp:1}"
1567 fi
1568 if [[ $sl_test_hook ]]; then
1569 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
1570 fi
1571
1572 if $haveinfo && [[ $type == b ]]; then
1573 info_sec=${tmp::10}
1574 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
1575 files_sec=${files_sec%%.*}
1576 if (( files_sec > info_sec )); then
1577 dorsync=true
1578 rm -f $sshinfo
1579 fi
1580 fi
1581
1582 sync_dirname=${SL_FILES_DIR##*/}
1583
1584 if [[ ! $SL_FILES_DIR ]]; then
1585 echo error: missing '$SL_FILES_DIR' env var >&2
1586 return 1
1587 fi
1588
1589 if $dorsync; then
1590 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
1591 fi
1592 if $dorsync || ! $haveinfo; then
1593 sshinfo=$SL_INFO_DIR/$now$type"$remote"
1594 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
1595 printf "%s\n" "$extra_info" >$sshinfo
1596 chmod 666 $sshinfo
1597 fi
1598 if [[ $type == b ]]; then
1599 if (( ${#@} )); then
1600 # Theres a couple ways to pass arguments, im not sure whats best,
1601 # but relying on bash 4.4+ escape quoting seems most reliable.
1602 command ssh "${args[@]}" "$remote" \
1603 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
1604 elif [[ ! -t 0 ]]; then
1605 # This case is when commands are being piped to ssh.
1606 # Normally, no bashrc gets sourced.
1607 # But, since we are doing all this, lets source it because we can.
1608 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1609 else
1610 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
1611 fi
1612 else
1613 if [[ -t 0 ]]; then
1614 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
1615 else
1616 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1617 fi
1618 fi
1619 # this function inspired from https://github.com/Russell91/sshrc
1620 }
1621
1622 slr() {
1623 sl --rsync "$@"
1624 }
1625 sss() { # ssh solo
1626 sl -oControlMaster=no -oControlPath=/ "$@"
1627 }
1628 # kill off old shared socket then ssh
1629 ssk() {
1630 m ssh -O exit "$@" || [[ $? == 255 ]]
1631 m sl "$@"
1632 }
1633 ccomp ssh sl slr sss ssk
1634 # plain ssh
1635 ssh() {
1636 if [[ $TERM == alacritty ]]; then
1637 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
1638 else
1639 LC_USEBASHRC=t command ssh "$@"
1640 fi
1641 }
1642
1643
1644 slog() {
1645 # log with script. timing is $1.t and script is $1.s
1646 # -l to save to ~/typescripts/
1647 # -t to add a timestamp to the filenames
1648 local logdir do_stamp arg_base
1649 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1650 logdir="/a/dt/"
1651 do_stamp=false
1652 while getopts "lt" option
1653 do
1654 case $option in
1655 l ) arg_base=$logdir ;;
1656 t ) do_stamp=true ;;
1657 esac
1658 done
1659 shift $((OPTIND - 1))
1660 arg_base+=$1
1661 [[ -e $logdir ]] || mkdir -p $logdir
1662 $do_stamp && arg_base+=$(date +%F.%T%z)
1663 script -t $arg_base.s 2> $arg_base.t
1664 }
1665 splay() { # script replay
1666 #logRoot="$HOME/typescripts/"
1667 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1668 scriptreplay "$1.t" "$1.s"
1669 }
1670
1671 sr() {
1672 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1673 if [[ $# == 0 ]]; then
1674 sudo -E bash -c -l "$(history -p '!!')"
1675 else
1676 echo this command redos last history item. no argument is accepted
1677 fi
1678 }
1679
1680 srm () {
1681 # with -ll, less secure but faster.
1682 command srm -ll "$@"
1683 }
1684
1685 srun() {
1686 scp $2 $1:/tmp
1687 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1688 }
1689
1690
1691 swap() {
1692 local tmp
1693 tmp=$(mktemp)
1694 mv $1 $tmp
1695 mv $2 $1
1696 mv $tmp $2
1697 }
1698
1699 tclock() { # terminal clock
1700 local x
1701 clear
1702 date +%l:%_M
1703 len=60
1704 # this goes to full width
1705 #len=${1:-$((COLUMNS -7))}
1706 x=1
1707 while true; do
1708 if (( x == len )); then
1709 end=true
1710 d="$(date +%l:%_M) "
1711 else
1712 end=false
1713 d=$(date +%l:%M:%_S)
1714 fi
1715 echo -en "\r"
1716 echo -n "$d"
1717 for ((i=0; i<x; i++)); do
1718 if (( i % 6 )); then
1719 echo -n _
1720 else
1721 echo -n .
1722 fi
1723 done
1724 if $end; then
1725 echo
1726 x=1
1727 else
1728 x=$((x+1))
1729 fi
1730 sleep 5
1731 done
1732 }
1733
1734
1735 te() {
1736 # test existence / exists
1737 local ret=0
1738 for x in "$@"; do
1739 [[ -e "$x" || -L "$x" ]] || ret=1
1740 done
1741 return $ret
1742 }
1743
1744 psoff() {
1745 # normally, i would just execute these commands in the function.
1746 # however, DEBUG is not inherited, so we need to run it outside a function.
1747 # And we want to run set -x afterwards to avoid spam, so we cram everything
1748 # in here, and then it will run after this function is done.
1749 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
1750 }
1751 pson() {
1752 PROMPT_COMMAND=prompt-command
1753 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1754 trap 'settitle "$BASH_COMMAND"' DEBUG
1755 fi
1756 }
1757
1758 tx() { # toggle set -x, and the prompt so it doesnt spam
1759 if [[ $- == *x* ]]; then
1760 set +x
1761 pson
1762 else
1763 psoff
1764 fi
1765 }
1766
1767 psnetns() {
1768 # show all processes in the network namespace $1.
1769 # blank entries appear to be subprocesses/threads
1770 local x netns
1771 netns=$1
1772 ps -w | head -n 1
1773 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1774 while read -r l; do
1775 x=$(ps -w --no-headers -p $l);
1776 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1777 done
1778 }
1779
1780 m() { printf "%s\n" "$*"; "$@"; }
1781
1782 uptime() {
1783 if type -p uprecords &>/dev/null; then
1784 uprecords -B
1785 else
1786 command uptime
1787 fi
1788 }
1789
1790 virshrm() {
1791 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1792 }
1793
1794 vm-set-listen(){
1795 local t
1796 t=$(mktemp)
1797 local vm=$1
1798 local ip=$2
1799 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1800 sed -r "s/listen='[^']+/listen='$ip/"> $t
1801 sudo virsh undefine $vm
1802 sudo virsh define $t
1803 }
1804
1805
1806 vmshare() {
1807 vm-set-listen $1 0.0.0.0
1808 }
1809
1810
1811 vmunshare() {
1812 vm-set-listen $1 127.0.0.1
1813 }
1814
1815 myiwscan() {
1816 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
1817 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
1818 sudo iw dev wls1 scan | sed -rn "
1819 s/^\Wcapability: (.*)/\1/;Ta;h;b
1820 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
1821 # padded to min width of 20
1822 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
1823 "|sort -r
1824 }
1825
1826 # * misc stuff
1827
1828
1829 # temporary variables to test colorization
1830 # some copied from gentoo /etc/bash/bashrc,
1831 use_color=false
1832 # dircolors --print-database uses its own built-in database
1833 # instead of using /etc/DIR_COLORS. Try to use the external file
1834 # first to take advantage of user additions.
1835 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1836 match_lhs=""
1837 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1838 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1839 [[ -z ${match_lhs} ]] \
1840 && type -P dircolors >/dev/null \
1841 && match_lhs=$(dircolors --print-database)
1842 # test if our $TERM is in the TERM values in dircolor
1843 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1844
1845
1846 if ${use_color} && [[ $- == *i* ]]; then
1847
1848 term_bold="$(tput bold)"
1849 term_red="$(tput setaf 1)"
1850 term_green="$(tput setaf 2)"
1851 term_yellow="$(tput setaf 3)"
1852 term_purple="$(tput setaf 5)"
1853 term_nocolor="$(tput sgr0)" # no font attributes
1854
1855 # unused so far. commented for shellcheck
1856 # term_underl="$(tput smul)"
1857 # term_blue="$(tput setaf 4)"
1858 # term_cyan="$(tput setaf 6)"
1859
1860 fi
1861 # Try to keep environment pollution down, EPA loves us.
1862 unset safe_term match_lhs use_color
1863
1864 # * prompt
1865
1866
1867 if [[ $- == *i* ]]; then
1868
1869 # this needs to come before next ps1 stuff
1870 # this stuff needs bash 4, feb 2009,
1871 # old enough to no longer condition on $BASH_VERSION anymore
1872 shopt -s autocd
1873 shopt -s dirspell
1874 PS1='\w'
1875 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
1876 PROMPT_DIRTRIM=2
1877 bind -m vi-command B:shell-backward-word
1878 bind -m vi-command W:shell-forward-word
1879 fi
1880
1881 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1882 unset PROMPT_DIRTRIM
1883 PS1="\h:$PS1"
1884 fi
1885
1886 # emacs terminal has problems if this runs slowly,
1887 # so I've thrown a bunch of things at the wall to speed it up.
1888 prompt-command() {
1889 local return=$? # this MUST COME FIRST
1890 local ps_char ps_color
1891 unset IFS
1892
1893 if [[ $HISTFILE ]]; then
1894 history -a # save history
1895 fi
1896
1897 # assigned in brc2
1898 # shellcheck disable=SC1303
1899 if [[ $jr_pid ]]; then
1900 if [[ -e /proc/$jr_pid ]]; then
1901 kill $jr_pid
1902 fi
1903 unset jr_pid
1904 fi
1905
1906 case $return in
1907 0) ps_color="$term_purple"
1908 ps_char='\$'
1909 ;;
1910 1) ps_color="$term_green"
1911 ps_char="$return \\$"
1912 ;;
1913 *) ps_color="$term_yellow"
1914 ps_char="$return \\$"
1915 ;;
1916 esac
1917 if [[ ! -O . ]]; then # not owner
1918 if [[ -w . ]]; then # writable
1919 ps_color="$term_bold$term_red"
1920 else
1921 ps_color="$term_bold$term_green"
1922 fi
1923 fi
1924
1925 # faster than sourceing the file im guessing
1926 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
1927 eval $(< /dev/shm/iank-status)
1928 fi
1929 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1930 ps_char="@ $ps_char"
1931 fi
1932 # We could test if sudo is active with sudo -nv
1933 # but then we get an email and log of lots of failed sudo commands.
1934 # We could turn those off, but seems better not to.
1935 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
1936 ps_char="SUDO $ps_char"
1937 fi
1938 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1939
1940 # set titlebar. instead, using more advanced
1941 # titelbar below
1942 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
1943 }
1944 PROMPT_COMMAND=prompt-command
1945
1946 if [[ $TERM == screen* ]]; then
1947 _title_escape="\033]..2;"
1948 else
1949 # somme sites recommend this, i dunno what the diff is.
1950 #_title_escape="\033]30;"
1951 _title_escape="\033]0;"
1952 fi
1953
1954 settitle () {
1955 # this makes it so we show the current command if
1956 # one is running, otherwise, show nothing
1957
1958 if [[ $1 == prompt-command ]]; then
1959 return 0
1960 fi
1961 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
1962 echo -ne "$_title_escape ${PWD/#$HOME/~} "
1963 printf "%s" "$*"
1964 echo -ne "\007"
1965 fi
1966 }
1967
1968 # note, this wont work:
1969 # x=$(mktemp); cp a $x
1970 # I havnt figured out why, bigger fish to fry.
1971 #
1972 # for titlebar.
1973 # condition from the screen man page i think.
1974 # note: duplicated in tx()
1975 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1976 trap 'settitle "$BASH_COMMAND"' DEBUG
1977 else
1978 trap DEBUG
1979 fi
1980
1981 fi
1982
1983 # * stuff that makes sense to be at the end
1984
1985
1986 # best practice
1987 unset IFS
1988
1989 # shellcheck disable=SC1090
1990 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
1991
1992 # I had this idea to start a bash shell which would run an initial
1993 # command passed through this env variable, then continue on
1994 # interactively. But the use case I had in mind went away.
1995 #
1996 # if [[ $MY_INIT_CMD ]]; then
1997 # "${MY_INIT_CMD[@]}"
1998 # unset MY_INIT_CMD
1999 # fi
2000
2001 # ensure no bad programs appending to this file will have an affect
2002 return 0