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