fixes to last commit
[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
7 # Use source ~/.bashrc instead of doing bash -l when running a script
8 # so this can set extdebug and avoid the bash debugger.
9 if [[ -s /a/bin/errhandle/err ]]; then
10 source /a/bin/errhandle/err
11 elif [[ -s ~/.iank/err ]]; then
12 # shellcheck source=/a/bin/errhandle/err
13 source ~/.iank/err
14 fi
15
16 # In t8, it runs clear_console for login shells by default. I don't want
17 # my console cleared. And linux ttys get cleared without this.
18 if shopt login_shell >/dev/null && [[ -e ~/.bash_logout ]]; then
19 rm ~/.bash_logout
20 fi
21
22 # for testing error catching:
23 # t2() {
24 # echo t2
25 # grep sdf sdfd
26 # echo wtf
27 # }
28 # t1() {
29 # echo t1
30 # t2 a b c
31 # }
32
33 # * settings
34
35 CDPATH=.
36
37 # remove all aliases. aliases provided by the system tend to get in the way,
38 # for example, error happens if I try to define a function the same name as an alias
39 unalias -a
40
41 # remove gnome keyring warning messages
42 # there is probably a more proper way, but I didnt find any easily on google
43 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
44 #unset GNOME_KEYRING_CONTROL
45
46 # use extra globing features.
47 shopt -s extglob
48 # include .files when globbing, but ignore files name . and ..
49 # setting this also sets dotglob.
50 export GLOBIGNORE="*/.:*/.."
51
52 # broken with bash_completion package. Saw a bug for this once. dont anymore.
53 # still broken in wheezy
54 # still buggered in latest stable from the web, version 2.1
55 # perhaps its fixed in newer git version, which fails to make for me
56 # this note is from 6-2014.
57 # still broken in flidas.
58 #shopt -s nullglob
59
60 # make tab on an empty line do nothing
61 shopt -s no_empty_cmd_completion
62
63 # fix spelling errors for cd, only in interactive shell
64 shopt -s cdspell
65 # append history instead of overwritting it
66 shopt -s histappend
67 # for compatibility, per gentoo/debian bashrc
68 shopt -s checkwinsize
69 # attempt to save multiline single commands as single history entries.
70 shopt -s cmdhist
71 # enable **
72 shopt -s globstar
73
74
75 # inside emacs fixes
76 if [[ $RLC_INSIDE_EMACS ]]; then
77 # EMACS is used by bash on startup, but we dont need it anymore.
78 # plus I hit a bug in a makefile which inherited it
79 unset EMACS
80 export RLC_INSIDE_EMACS
81 export PAGER=cat
82 export MANPAGER=cat
83 # scp completion does not work, but this doesnt fix it. todo, figure this out
84 #complete -r scp &> /dev/null
85 # todo, remote file completion fails, figure out how to turn it off
86 export NODE_DISABLE_COLORS=1
87 # This gets rid of ugly terminal escape chars in node repl
88 # sometime, Id like to have completion working in emacs shell for node
89 # the offending chars can be found in lib/readline.js,
90 # things that do like:
91 # stream.write('\x1b[' + (x + 1) + 'G');
92 # We can remove them and keep readline, for example by doing this
93 # to start a repl:
94 #!/usr/bin/env nodejs
95 # var readline = require('readline');
96 # readline.cursorTo = function(a,b,c) {};
97 # readline.clearScreenDown = function(a) {};
98 # const repl = require('repl');
99 # var replServer = repl.start('');
100 #
101 # no prompt, or else readline complete seems to be confused, based
102 # on our column being different? node probably needs to send
103 # different kind of escape sequence that is not ugly. Anyways,
104 # completion doesnt work yet even with the ugly prompt, so whatever
105 #
106 export NODE_NO_READLINE=1
107
108 fi
109
110 # emacs has a different default search path than the info command. This
111 # adds the info defaults to emacs, but not the reverse, because I dun
112 # care much about the cli. The search path is only on the cli if you run
113 # "info xxx", or in emacs if you run '(info xxx)', so not that
114 # important, but might as well fix it.
115
116 # info info says this path is what was compiled, and its not documented
117 # anywhere. Through source grepping, i found it in filesys.h of the info
118 # source in trisquel flidas.
119 #
120 # Traling : means for emacs to add its own stuff on to the end.
121
122 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:.:
123
124 if [[ $- == *i* ]]; then
125 # for readline-complete.el
126 if [[ $RLC_INSIDE_EMACS ]]; then
127 # all for readline-complete.el
128 stty echo
129 bind 'set horizontal-scroll-mode on'
130 bind 'set print-completions-horizontally on'
131 bind '"\C-i": self-insert'
132 else
133
134 if [[ $KONSOLE_PROFILE_NAME ]]; then
135 TERM=xterm-256color
136 fi
137
138 # todo: not sure this works in sakura
139 #stty werase undef
140 #bind "\C-w": kill-region
141 # sakura == xterm-256color
142 # konsole == xterm
143 if [[ $TERM == xterm* ]]; then
144 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
145 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
146 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
147 else
148 # make ctrl-backspace work. for konsole, i fixed it through
149 # /home/iank/.local/share/konsole/default.keytab
150 stty werase '^h'
151 bind '"\eOc": shell-forward-word'
152 bind '"\eOd": shell-backward-word'
153 fi
154 # i cant remember why i did this, probably to free up some keys to bind
155 # to other things in bash.
156 # other than C-c and C-z, the rest defined by stty -a are, at least in
157 # gnome-terminal, overridden by bash, or disabled by the system
158 stty lnext undef stop undef start undef
159 fi
160
161 fi
162
163 export BC_LINE_LENGTH=0
164
165 # ansible option
166 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
167
168 # note, if I use a machine I dont want files readable by all users, set
169 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
170
171 # i for insensitive. the rest from
172 # X means dont remove the current screenworth of output upon exit
173 # R means to show colors n things
174 export LESS=RXi
175 export SYSTEMD_LESS=$LESS
176
177
178 # * include files
179
180
181
182 # if someone exported $SOE (stop on error), catch errors.
183 #
184 # Note, on debian this results in the following warning when in ssh,
185 # hich I haven't figured out how to fix. It doesn't happen if we source
186 # after the shell has started
187 #
188 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
189 # bash: warning: cannot start debugger; debugging mode disabled
190 if [[ $SOE ]]; then
191 if [[ -e /a/bin/errhandle/err ]]; then
192 source /a/bin/errhandle/err
193 fi
194 fi
195
196 # based on readme.debian. dunno if this will break on other distros.
197 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
198 source /usr/share/wcd/wcd-include.sh
199 fi
200
201 if [[ -s /a/bin/small-misc-bash/ll-function ]]; then
202 source /a/bin/small-misc-bash/ll-function
203 elif [[ -s ~/.iank/ll-function ]]; then
204 # shellcheck source=/a/bin/small-misc-bash/ll-function
205 source ~/.iank/ll-function
206 fi
207
208
209 # * functions
210
211
212 ..() { c ..; }
213 ...() { c ../..; }
214 ....() { c ../../..; }
215 .....() { c ../../../..; }
216 ......() { c ../../../../..; }
217
218 # file cut copy and paste, like the text buffers :)
219 # I havnt tested these.
220 _fbufferinit() { # internal use
221 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
222 rm -rf "${my_f_tempdir:?}"/*
223 }
224 fcp() { # file cp
225 _fbufferinit
226 cp "$@" "$my_f_tempdir"/
227 }
228 fct() { # file cut
229 _fbufferinit
230 mv "$@" "$my_f_tempdir"/
231 }
232 fpst() { # file paste
233 [[ $2 ]] && { echo too many arguments; return 1; }
234 target=${1:-.}
235 cp "$my_f_tempdir"/* "$target"
236 }
237
238 _khfix_common() {
239 local host=${1##*@}
240 local ip port
241 read -r ip port < <(timeout 1 ssh -oBatchMode=yes -oControlMaster=no -oControlPath=/ -v $1 |& sed -rn "s/debug1: Connecting to $host \[([^\]*)] port ([0-9]+).*/\1 \2/p")
242 if [[ ! $ip ]]; then
243 echo "khfix: ssh failed"
244 return 1
245 fi
246 if [[ $port != 22 ]]; then
247 ip_entry="[$ip]:$port"
248 host_entry="[$host]:$port"
249 else
250 ip_entry=$ip
251 host_entry=$host
252 fi
253 ssh-keygen -R "$host_entry" -f $(readlink -f ~/.ssh/known_hosts)
254 echo "khfix: removing key for $ip_entry"
255 ssh-keygen -R "$ip_entry" -f $(readlink -f ~/.ssh/known_hosts)
256 }
257 khfix() { # known hosts fix
258 _khfix_common "$@" || return 1
259 ssh $1 :
260 }
261 khcopy() {
262 _khfix_common "$@"
263 ssh-copy-id $1
264 }
265
266 a() {
267 local x
268 x=$(readlink -nf "${1:-$PWD}")
269 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
270 echo -n "$x" | xclip -selection clipboard
271 echo -n "$x" | xclip
272 }
273
274 ack() { ack-grep "$@"; }
275
276 b() {
277 # backwards
278 c -
279 }
280
281
282 # c. better cd
283 if type -p wcd &>/dev/null; then
284 if [[ $RLC_INSIDE_EMACS ]]; then
285 c() { wcd -c -z 50 -o "$@"; }
286 else
287 # lets see what the fancy terminal does from time to time
288 c() { wcd -c -z 50 "$@"; }
289 fi
290 else
291 c() { cd "$@"; }
292 fi
293
294 c4() { c /var/log/exim4; }
295
296 caa() { git commit --amend --no-edit -a; }
297
298 caf() {
299 # shellcheck disable=SC2033
300 find -L $1 -type f -not \( -name .svn -prune -o -name .git -prune \
301 -o -name .hg -prune -o -name .editor-backups -prune \
302 -o -name .undo-tree-history -prune \) \
303 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
304
305 }
306
307 calc() { echo "scale=3; $*" | bc -l; }
308 # no having to type quotes, but also no command history:
309 clc() {
310 local x
311 read -r x
312 echo "scale=3; $x" | bc -l
313 }
314
315 cam() {
316 git commit -am "$*"
317 }
318
319
320 ccat () { # config cat. see a config without extra lines.
321 grep '^\s*[^;[:space:]#]' "$@" || [[ $? == 1 ]]
322 }
323
324
325 _cdiff-prep() {
326 # join options which are continued to multiples lines onto one line
327 local first=true
328 while IFS= read -r line; do
329 # remove leading spaces/tabs. assumes extglob
330 if [[ $line == "[ ]*" ]]; then
331 line="${line##+( )}"
332 fi
333 if $first; then
334 pastline="$line"
335 first=false
336 elif [[ $line == *=* ]]; then
337 echo "$pastline" >> "$2"
338 pastline="$line"
339 else
340 pastline="$pastline $line"
341 fi
342 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
343 echo "$pastline" >> "$2"
344 }
345
346 cdiff() {
347 # diff config files,
348 # setup for format of postfix, eg:
349 # option = stuff[,]
350 # [more stuff]
351 local pastline unified f1 f2
352 unified="$(mktemp)"
353 f1="$(mktemp)"
354 f2="$(mktemp)"
355 _cdiff-prep "$1" "$f1"
356 _cdiff-prep "$2" "$f2"
357 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
358 while IFS= read -r line; do
359 # the default bright red / blue doesnt work in emacs shell
360 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
361 done < "$unified"
362 }
363
364
365 cat-new-files() {
366 local start=$SECONDS
367 local dir="$1"
368 inotifywait -m "$dir" -e create -e moved_to |
369 # shellcheck disable=SC2030
370 while read -r filedir _ file; do
371 cat "$filedir$file"
372 hr
373 calc $((SECONDS - start)) / 60
374 sleep 5
375 done
376
377 }
378
379 # shellcheck disable=SC2032
380 chown() {
381 # makes it so chown -R symlink affects the symlink and its target.
382 if [[ $1 == -R ]]; then
383 shift
384 command chown -h "$@"
385 command chown -R "$@"
386 else
387 command chown "$@"
388 fi
389 }
390
391 cim() {
392 git commit -m "$*"
393 }
394
395 cl() {
396 # choose recent directory. cl = cd list
397 c =
398 }
399
400 d() { builtin bg; }
401 complete -A stopped -P '"%' -S '"' d
402
403
404 dc() {
405 diff --strip-trailing-cr -w "$@" # diff content
406 }
407
408 despace() {
409 local x y
410 for x in "$@"; do
411 y="${x// /_}"
412 safe_rename "$x" "$y"
413 done
414 }
415
416 dig() {
417 command dig +nostats +nocmd "$@"
418 }
419 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
420 digsort() {
421 local sec
422 sec=
423 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
424 if [[ $l == [^\;]* ]]; then
425 sec+="$l"$'\n'
426 else
427 if [[ $sec ]]; then
428 printf "%s" "$sec" | sort
429 sec=
430 fi
431 printf "%s\n" "$l"
432 fi
433 done
434 }
435 # compare digs to the 2 servers
436 # usage: digdiff @server1 @server2 DIG_ARGS
437 # note: only the soa master nameserver will respond with
438 # ra "recursive answer" flag. That difference is meaningless afaik.
439 digdiff() {
440 local s1 s2
441 s1=$1
442 shift
443 s2=$1
444 shift
445 digsort $s1 "$@" | tee /tmp/digdiff
446 diff -u /tmp/digdiff <(digsort $s2 "$@")
447 }
448
449 dt() {
450 date "+%A, %B %d, %r" "$@"
451 }
452
453 dus() { # du, sorted, default arg of
454 du -sh ${@:-*} | sort -h
455 }
456
457
458
459 e() { echo "$@"; }
460
461 # echo args
462 ea() {
463 if (( ! $# )); then
464 echo no args
465 fi
466 for arg; do
467 printf "%qEOL\n" "${arg}"
468 printf "%s" "${arg}" |& hexdump -C
469 done
470 }
471 # echo vars. print var including escapes, etc
472 ev() {
473 if (( ! $# )); then
474 echo no args
475 fi
476 for arg; do
477 printf "%qEOL\n" "${!arg}"
478 printf "%s" "${!arg}" |& hexdump -C
479 done
480 }
481
482 ediff() {
483 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
484 emacs --eval "(ediff-files \"$1\" \"$2\")"
485 }
486
487 # mail related
488 etail() {
489 tail -F /var/log/exim4/mainlog -n 200
490 }
491 eless() {
492 less /var/log/exim4/mainlog
493 }
494 eqcat() {
495 exiqgrep -i | while read -r i; do
496 exim -Mvh $i; hr; exim -Mvb $i; hr;
497 exigrep $i /var/log/exim4/mainlog; hr
498 done
499 }
500
501
502 # shellcheck disable=SC2032
503 f() {
504 # cd forward
505 c +
506 }
507
508 fa() {
509 # find array. make an array of file names found by find into $x
510 # argument: find arguments
511 # return: find results in an array $x
512 while read -rd ''; do
513 x+=("$REPLY");
514 done < <(find "$@" -print0);
515 }
516
517 faf() { # find all files. use -L to follow symlinks
518 find $@ -not \( -name .svn -prune -o -name .git -prune \
519 -o -name .hg -prune -o -name .editor-backups -prune \
520 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
521 }
522
523 # mail related
524 frozen() {
525 rm -rf /tmp/frozen
526 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
527 sudo exim -Mvl $id
528 echo
529 sudo exim -Mvh $id
530 echo
531 sudo exim -Mvb $id
532 echo -e '\n\n##############################\n'
533 done | tee -a /tmp/frozen
534 }
535 frozenrm() {
536 local ids=()
537 while read -r line; do
538 printf '%s\n' "$line"
539 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
540 done < <(s mailq)
541 echo "sleeping for 2 in case you change your mind"
542 sleep 2
543 sudo exim -Mrm "${ids[@]}"
544 }
545
546 funce() {
547 # like -e for functions. returns on error.
548 # at the end of the function, disable with:
549 # trap ERR
550 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
551 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
552 trap ERR
553 return' ERR
554 }
555
556 getdir () {
557 local help="Usage: getdir [--help] PATH
558 Output the directory of PATH, or just PATH if it is a directory."
559 if [[ $1 == --help ]]; then
560 echo "$help"
561 return 0
562 fi
563 if [[ $# -ne 1 ]]; then
564 echo "getdir error: expected 1 argument, got $#"
565 return 1
566 fi
567 if [[ -d $1 ]]; then
568 echo "$1"
569 else
570 local dir
571 dir="$(dirname "$1")"
572 if [[ -d $dir ]]; then
573 echo "$dir"
574 else
575 echo "getdir error: directory does not exist"
576 return 1
577 fi
578 fi
579 }
580
581 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
582 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
583 local root
584 root=$(gitroot) || return 1 # function to set gitroot
585 builtin cd "$root"
586 git symbolic-ref HEAD refs/heads/$1
587 rm .git/index
588 git clean -fdx
589 }
590
591 # shellcheck disable=SC2120
592 gitroot() {
593 local help="Usage: gitroot [--help]
594 Print the full path to the root of the current git repo
595
596 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
597 and works in older versions of git which did not have that."
598 if [[ $1 == --help ]]; then
599 echo "$help"
600 return
601 fi
602 local p
603 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
604 [[ $p != /* ]] && p=$PWD
605 echo "${p%%/.git}"
606 }
607
608 gh() {
609 # i got an error, gh not found when doing a pull request, it seems like it wants itself in it\'s path.
610 local _oldpath="$PATH"
611 PATH="$PATH:$HOME/node_modules/.bin"
612 command gh "$@"
613 PATH="$_oldpath"
614 }
615
616 gmacs() {
617 # quit will prompt if the program crashes.
618 gdb -ex=r -ex=quit --args emacs "$@"; r;
619 }
620
621 gdkill() {
622 # kill the emacs daemon
623 pk1 emacs --daemon
624 }
625
626 gr() {
627 grep -iIP --color=auto "$@"
628 }
629
630 grr() { # grep recursive
631 # Don't return 1 on nonmatch because this is meant to be
632 # interactive, not in a conditional.
633 if [[ ${#@} == 1 ]]; then
634 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" . || [[ $? == 1 ]]
635 else
636 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" || [[ $? == 1 ]]
637 fi
638 }
639 rg() {
640 command rg -i -M 200 "$@"
641 }
642
643 hr() { # horizontal row. used to break up output
644
645 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
646 echo
647 }
648
649 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
650
651 # get latest hub and run it
652 # main command to use:
653 # hub pull-request --no-edit
654 # --no-edit means to use the first commit\'s message as the pull request message.
655 # Also, you need to use a feature branch, not master in your fork.
656 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
657 # it\'s at ~/.config/hub
658 hub() {
659 local up uptar updir p
660 p=/github/hub/releases/
661 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
662 uptar=${up##*/}
663 updir=${uptar%.tgz}
664 if [[ ! -e /a/opt/$updir ]]; then
665 rm -rf /a/opt/hub-linux-amd64*
666 wget -P /a/opt $up
667 tar -C /a/opt -zxf /a/opt/$uptar
668 rm -f /a/opt/$uptar
669 sudo /a/opt/$updir/install
670 fi
671
672 # save token across computers
673 if [[ ! -L ~/.config/hub ]]; then
674 if [[ -e ~/.config/hub ]]; then
675 mv ~/.config/hub /p/c/subdir_files/.config/
676 fi
677 if [[ -e /p/c/subdir_files/.config/hub ]]; then
678 conflink
679 fi
680 fi
681 command hub "$@"
682 }
683
684 i() { git "$@"; }
685 # modified from ~/local/bin/git-completion.bash
686 # other completion commands are mostly taken from bash_completion package
687 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
688 || complete -o default -o nospace -F _git i
689
690 if ! type service &>/dev/null; then
691 service() {
692 echo actually running: systemctl $2 $1
693 systemctl $2 $1
694 }
695 fi
696
697
698
699 ic() {
700 # fast commit all
701 git commit -am "$*"
702 }
703
704
705
706 ifn() {
707 # insensitive find
708 find -L . -not \( -name .svn -prune -o -name .git -prune \
709 -o -name .hg -prune -o -name .editor-backups -prune \
710 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
711 }
712
713 ipdrop() {
714 sudo iptables -A INPUT -s $1 -j DROP
715 }
716
717
718 istext() {
719 grep -Il "" "$@" &>/dev/null
720 }
721
722 jtail() {
723 journalctl -n 10000 -f "$@"
724 }
725 jr() { journalctl "$@" ; }
726 jrf() { journalctl -f "$@" ; }
727
728 l() {
729 if [[ $PWD == /[iap] ]]; then
730 command ls -A --color=auto -I lost+found "$@"
731 else
732 command ls -A --color=auto "$@"
733 fi
734 }
735
736
737 lcn() { locate -i "*$**"; }
738
739 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first; }
740
741 lt() { ll -tr "$@"; }
742
743 lld() { ll -d "$@"; }
744
745 low() { # make filenames lowercase, remove bad chars
746 local f new
747 for f in "$@"; do
748 new="${f,,}" # downcase
749 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
750 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
751 new="${new%"${new##*[[:alnum:]]}"}"
752 # remove bad underscores, like __ and _._
753 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
754 safe_rename "$f" "$new" || return 1
755 done
756 return 0
757 }
758
759 lower() { # make first letter of filenames lowercase.
760 local x
761 for x in "$@"; do
762 if [[ ${x::1} == [A-Z] ]]; then
763 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
764 safe_rename "$x" "$y" || return 1
765 fi
766 done
767 }
768
769
770 k() { # history search
771 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
772 }
773
774 ks() { # history search
775 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
776 }
777
778
779 make-targets() {
780 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
781 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
782 }
783
784 mkc() {
785 mkdir "$1"
786 c "$1"
787 }
788
789 mkct() {
790 mkc $(mktemp -d)
791 }
792
793 mkt() { # mkdir and touch file
794 local path="$1"
795 mkdir -p "$(dirname "$path")"
796 touch "$path"
797 }
798
799 # shellcheck disable=SC2032
800 mkdir() { command mkdir -p "$@"; }
801
802 nopanic() {
803 # shellcheck disable=SC2024
804 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
805 }
806
807 p8() { ping 8.8.8.8; }
808 p6() { ping6 2001:4860:4860::8888; }
809
810 pkx() { # package extract
811 local pkg cached tmp f
812 c $(mktemp -d)
813 pkg=$1
814 # shellcheck disable=SC2012
815 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
816 if [[ $cached ]]; then
817 cp $cached .
818 else
819 aptitude download $pkg || return 1
820 fi
821 tmp=(*); f=${tmp[0]} # only 1 expected
822 ex $f
823 rm -f $f
824 }
825
826 # pgrep and kill
827 pk1() {
828 local pid
829 pid=($(pgrep -f "$*"))
830 case ${#pid[@]} in
831 1)
832 # shellcheck disable=SC2128
833 {
834 ps -F $pid
835 m kill $pid
836 }
837 ;;
838 0) echo "no pid found" ;;
839 *)
840 ps -F ${pid[@]}
841 ;;
842 esac
843 }
844
845 psg () {
846 local x y help
847 help="Usage: psg [--help] GREP_ARGS
848 grep ps and output in a nice format"
849 if [[ $1 == --help ]]; then
850 echo "$help"
851 return
852 fi
853 x=$(sudo ps -eF)
854 # final grep is because some commands tend to have a lot of trailing spaces
855 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
856 if [[ $y ]]; then
857 echo "$x" | head -n 1 || [[ $? == 141 ]]
858 echo "$y"
859 fi
860 }
861
862 pubip() { curl -4s https://icanhazip.com; }
863 pubip6() { curl -6s https://icanhazip.com; }
864 whatismyip() { pubip; }
865
866 pwgen() {
867 # -m = min length
868 # -x = max length
869 # -t = print pronunciation
870 apg -m 14 -x 17 -t
871 for (( i=0; i<10; i++ )); do
872 shuf -n3 /usr/share/hunspell/en_US.dic | sed 's,/.*,,' | paste -sd . -
873
874 done
875 }
876
877 pwlong() {
878 # -M CLN = use Caps, Lowercase, Numbers
879 # -n 1 = 1 password
880 # -a 1 = use random instead of pronounceable algorithm
881 apg -m 50 -x 70 -n 1 -a 1 -M CLN
882 }
883
884
885 q() { # start / launch a program in the backround and redir output to null
886 "$@" &> /dev/null &
887 }
888
889 # shellcheck disable=SC2120
890 r() {
891 if [[ $HISTFILE ]]; then
892 history -a # save history
893 fi
894 trap ERR # this avoids a segfault
895 exit ${1:0}
896 # i had this redir, not sure why
897 # exit "$@" 2>/dev/null
898 }
899
900 rl() {
901 # rsync, root is required to keep permissions right.
902 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
903 # --no-times --delete
904 # basically, make an exact copy, use checksums instead of file times to be more accurate
905 rsync -ahvic --delete "$@"
906 }
907 rld() {
908 # like rlu, but dont delete files on the target end which
909 # do not exist on the original end.
910 rsync -ahvic "$@"
911 }
912 complete -F _rsync -o nospace rld rl rlt
913
914 rlt() {
915 # rl without preserving modification time.
916 rsync -ahvic --delete --no-t "$@"
917 }
918
919 rlu() { # [OPTS] HOST PATH
920 # eg. rlu -opts frodo /testpath
921 # relative paths will expanded with readlink -f.
922 opts=("${@:1:$#-2}") # 1 to last -2
923 path="${*:$#}" # last
924 host="${*:$#-1:1}" # last -1
925 if [[ $path == .* ]]; then
926 path=$(readlink -f $path)
927 fi
928 # rync here uses checksum instead of time so we dont mess with
929 # unison relying on time as much. g is for group, same reason
930 # to keep up with unison.
931 sudo rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
932 }
933
934 rmstrips() {
935 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
936 }
937
938 s() {
939 # background
940 # I use a function because otherwise we cant use in a script,
941 # cant assign to variable.
942 #
943 # note: gksudo is recommended for X apps because it does not set the
944 # home directory to the same, and thus apps writing to ~ fuck things up
945 # with root owned files.
946 #
947 if [[ $EUID != 0 || $1 == -* ]]; then
948 # shellcheck disable=SC2034
949 SUDOD="$PWD" command sudo -i "$@"
950 else
951 "$@"
952 fi
953 }
954
955 safe_rename() { # warn and dont rename if file exists.
956 # mv -n exists, but it\'s silent
957 if [[ $# != 2 ]]; then
958 echo safe_rename error: $# args, need 2 >2
959 return 1
960 fi
961 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
962 if [[ -e $2 || -L $2 ]]; then
963 echo "Cannot rename $1 to $2 as it already exists."
964 else
965 mv -vi "$1" "$2"
966 fi
967 fi
968 }
969
970
971 sb() { # sudo bash -c
972 # use sb instead of s is for sudo redirections,
973 # eg. sb 'echo "ok fine" > /etc/file'
974 local SUDOD="$PWD"
975 sudo -i bash -c "$@"
976 }
977 complete -F _root_command s sb
978
979
980 ser() {
981 local s; [[ $EUID != 0 ]] && s=sudo
982 if type -p systemctl &>/dev/null; then
983 $s systemctl $1 $2
984 else
985 $s service $2 $1
986 fi
987 }
988 seru() { systemctl --user "$@"; }
989 # like restart, but do nothing if its not already started
990 srestart() {
991 local service=$1
992 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
993 systemctl restart $service
994 fi
995 }
996
997 setini() { # set a value in a .ini style file
998 key="$1" value="$2" section="$3" file="$4"
999 if [[ -s $file ]]; then
1000 sed -ri -f - "$file" <<EOF
1001 # remove existing keys
1002 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1003 # add key
1004 /^\s*\[$section\]/a $key=$value
1005 # from section to eof, do nothing
1006 /^\s*\[$section\]/,\$b
1007 # on the last line, if we haven't found section yet, add section and key
1008 \$a [$section]\\
1009 $key=$value
1010 EOF
1011 else
1012 cat >"$file" <<EOF
1013 [$section]
1014 $key=$value
1015 EOF
1016 fi
1017 }
1018
1019 sgo() { # service go
1020 service=$1
1021 ser restart $service || return 1
1022 if type -p systemctl &>/dev/null; then
1023 ser enable $service
1024 fi
1025 }
1026 soff() { # service go
1027 service=$1
1028 ser stop $service
1029 ser disable $service
1030 }
1031
1032 sgu() {
1033 systemctl list-unit-files | rg "$@"
1034 }
1035
1036
1037 sk() {
1038 # 2086: unquoted $var
1039 # 2046: unquoted $(cmd)
1040 # 2068: Double quote array expansions to avoid re-splitting elements.
1041 # 2119: Functions with optional args get bad warnings when none are passed.
1042 # 2033: too many false positives for thing that will never work, passing shell function to find.
1043 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1044 shellcheck -x -e 2086,2046,2068,2119,2033 "$@" || return $?
1045 # had this before. not sure what it is 2119
1046 }
1047
1048
1049 slog() {
1050 # log with script. timing is $1.t and script is $1.s
1051 # -l to save to ~/typescripts/
1052 # -t to add a timestamp to the filenames
1053 local logdir do_stamp arg_base
1054 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1055 logdir="/a/dt/"
1056 do_stamp=false
1057 while getopts "lt" option
1058 do
1059 case $option in
1060 l ) arg_base=$logdir ;;
1061 t ) do_stamp=true ;;
1062 esac
1063 done
1064 shift $((OPTIND - 1))
1065 arg_base+=$1
1066 [[ -e $logdir ]] || mkdir -p $logdir
1067 $do_stamp && arg_base+=$(date +%F.%T%z)
1068 script -t $arg_base.s 2> $arg_base.t
1069 }
1070 splay() { # script replay
1071 #logRoot="$HOME/typescripts/"
1072 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1073 scriptreplay "$1.t" "$1.s"
1074 }
1075
1076 sr() {
1077 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1078 if [[ $# == 0 ]]; then
1079 sudo -E bash -c -l "$(history -p '!!')"
1080 else
1081 echo this command redos last history item. no argument is accepted
1082 fi
1083 }
1084
1085 srm () {
1086 # with -ll, less secure but faster.
1087 command srm -ll "$@"
1088 }
1089
1090 srun() {
1091 scp $2 $1:/tmp
1092 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1093 }
1094
1095
1096 swap() {
1097 local tmp
1098 tmp=$(mktemp)
1099 mv $1 $tmp
1100 mv $2 $1
1101 mv $tmp $2
1102 }
1103
1104 tclock() { # terminal clock
1105 local x
1106 clear
1107 date +%l:%_M
1108 len=60
1109 # this goes to full width
1110 #len=${1:-$((COLUMNS -7))}
1111 x=1
1112 while true; do
1113 if (( x == len )); then
1114 end=true
1115 d="$(date +%l:%_M) "
1116 else
1117 end=false
1118 d=$(date +%l:%M:%_S)
1119 fi
1120 echo -en "\r"
1121 echo -n "$d"
1122 for ((i=0; i<x; i++)); do
1123 if (( i % 6 )); then
1124 echo -n _
1125 else
1126 echo -n .
1127 fi
1128 done
1129 if $end; then
1130 echo
1131 x=1
1132 else
1133 x=$((x+1))
1134 fi
1135 sleep 5
1136 done
1137 }
1138
1139
1140 te() {
1141 # test existence / exists
1142 local ret=0
1143 for x in "$@"; do
1144 [[ -e "$x" || -L "$x" ]] || ret=1
1145 done
1146 return $ret
1147 }
1148
1149
1150 tx() { # toggle set -x, and the prompt so it doesnt spam
1151 if [[ $- == *x* ]]; then
1152 set +x
1153 PROMPT_COMMAND=prompt-command
1154 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1155 trap 'settitle "$BASH_COMMAND"' DEBUG
1156 fi
1157 else
1158 # normally, i would just execute these commands in the function.
1159 # however, DEBUG is not inherited, so we need to run it outside a function.
1160 # And we want to run set -x afterwards to avoid spam, so we cram everything
1161 # in here, and then it will run after this function is done.
1162 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "; set -x'
1163 fi
1164 }
1165
1166 psnetns() {
1167 # show all processes in the network namespace $1.
1168 # blank entries appear to be subprocesses/threads
1169 local x netns
1170 netns=$1
1171 ps -w | head -n 1
1172 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1173 while read -r l; do
1174 x=$(ps -w --no-headers -p $l);
1175 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1176 done
1177 }
1178
1179 m() { printf "%s\n" "$*"; "$@"; }
1180
1181
1182 virshrm() {
1183 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1184 }
1185
1186 vm-set-listen(){
1187 local t
1188 t=$(mktemp)
1189 local vm=$1
1190 local ip=$2
1191 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1192 sed -r "s/listen='[^']+/listen='$ip/"> $t
1193 sudo virsh undefine $vm
1194 sudo virsh define $t
1195 }
1196
1197
1198 vmshare() {
1199 vm-set-listen $1 0.0.0.0
1200 }
1201
1202
1203 vmunshare() {
1204 vm-set-listen $1 127.0.0.1
1205 }
1206
1207 # * misc stuff
1208
1209
1210 # temporary variables to test colorization
1211 # some copied from gentoo /etc/bash/bashrc,
1212 use_color=false
1213 # dircolors --print-database uses its own built-in database
1214 # instead of using /etc/DIR_COLORS. Try to use the external file
1215 # first to take advantage of user additions.
1216 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1217 match_lhs=""
1218 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1219 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1220 [[ -z ${match_lhs} ]] \
1221 && type -P dircolors >/dev/null \
1222 && match_lhs=$(dircolors --print-database)
1223 # test if our $TERM is in the TERM values in dircolor
1224 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1225
1226
1227 if ${use_color} && [[ $- == *i* ]]; then
1228
1229 term_bold="$(tput bold)"
1230 term_red="$(tput setaf 1)"
1231 term_green="$(tput setaf 2)"
1232 term_yellow="$(tput setaf 3)"
1233 term_purple="$(tput setaf 5)"
1234 term_nocolor="$(tput sgr0)" # no font attributes
1235
1236 # unused so far. commented for shellcheck
1237 # term_underl="$(tput smul)"
1238 # term_blue="$(tput setaf 4)"
1239 # term_cyan="$(tput setaf 6)"
1240
1241 fi
1242 # Try to keep environment pollution down, EPA loves us.
1243 unset safe_term match_lhs use_color
1244
1245 # * prompt
1246
1247
1248 if [[ $- == *i* ]]; then
1249
1250 # this needs to come before next ps1 stuff
1251 # this stuff needs bash 4, feb 2009,
1252 # old enough to no longer condition on $BASH_VERSION anymore
1253 shopt -s autocd
1254 shopt -s dirspell
1255 PS1='\w'
1256 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1257 PROMPT_DIRTRIM=2
1258 bind -m vi-command B:shell-backward-word
1259 bind -m vi-command W:shell-forward-word
1260 fi
1261
1262 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1263 PS1="\h $PS1"
1264 fi
1265
1266 # emacs terminal has problems if this runs slowly,
1267 # so I've thrown a bunch of things at the wall to speed it up.
1268 prompt-command() {
1269 local return=$? # this MUST COME FIRST
1270 local ps_char ps_color
1271 unset IFS
1272
1273 if [[ $HISTFILE ]]; then
1274 history -a # save history
1275 fi
1276
1277 if [[ $jr_pid ]]; then
1278 if [[ -e /proc/$jr_pid ]]; then
1279 kill $jr_pid
1280 fi
1281 unset jr_pid
1282 fi
1283
1284 case $return in
1285 0) ps_color="$term_purple"
1286 ps_char='\$'
1287 ;;
1288 1) ps_color="$term_green"
1289 ps_char="$return \\$"
1290 ;;
1291 *) ps_color="$term_yellow"
1292 ps_char="$return \\$"
1293 ;;
1294 esac
1295 if [[ ! -O . ]]; then # not owner
1296 if [[ -w . ]]; then # writable
1297 ps_color="$term_bold$term_red"
1298 else
1299 ps_color="$term_bold$term_green"
1300 fi
1301 fi
1302
1303 # faster than sourceing the file im guessing
1304 if [[ -e /dev/shm/iank-status ]]; then
1305 eval $(< /dev/shm/iank-status)
1306 fi
1307 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1308 ps_char="@ $ps_char"
1309 fi
1310 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1311
1312 # set titlebar
1313 #echo -ne "$title_escape ${PWD/#$HOME/~} \007"
1314
1315 }
1316 PROMPT_COMMAND=prompt-command
1317
1318 if [[ $TERM == screen* ]]; then
1319 _title_escape="\033]..2;"
1320 else
1321 _title_escape="\033]0;"
1322 fi
1323
1324 settitle () {
1325 # this makes it so we show the current command if
1326 # one is running, otherwise, show nothing
1327 if [[ $1 == prompt-command ]]; then
1328 set --
1329 fi
1330 if [[ ${#BASH_ARGC[@]} == 1 ]]; then
1331 echo -ne "$_title_escape ${PWD/#$HOME/~} "
1332 printf "%s" "$*"
1333 echo -ne "\007"
1334 fi
1335 }
1336
1337 # for titlebar.
1338 # condition from the screen man page i think.
1339 # note: duplicated in tx()
1340 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1341 trap 'settitle "$BASH_COMMAND"' DEBUG
1342 else
1343 trap DEBUG
1344 fi
1345
1346 fi
1347
1348 # * stuff that makes sense to be at the end
1349
1350
1351 # best practice
1352 unset IFS
1353
1354 # shellcheck disable=SC1090
1355 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
1356
1357 # I had this idea to start a bash shell which would run an initial
1358 # command passed through this env variable, then continue on
1359 # interactively. But the use case I had in mind went away.
1360 #
1361 # if [[ $MY_INIT_CMD ]]; then
1362 # "${MY_INIT_CMD[@]}"
1363 # unset MY_INIT_CMD
1364 # fi
1365
1366 # ensure no bad programs appending to this file will have an affect
1367 return 0