fix jrun
[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
483 ediff() {
484 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
485 emacs --eval "(ediff-files \"$1\" \"$2\")"
486 }
487
488 # mail related
489 etail() {
490 tail -F /var/log/exim4/mainlog -n 200
491 }
492 eless() {
493 less /var/log/exim4/mainlog
494 }
495 eqcat() {
496 exiqgrep -i | while read -r i; do
497 exim -Mvh $i; hr; exim -Mvb $i; hr;
498 exigrep $i /var/log/exim4/mainlog; hr
499 done
500 }
501
502
503 # shellcheck disable=SC2032
504 f() {
505 # cd forward
506 c +
507 }
508
509 fa() {
510 # find array. make an array of file names found by find into $x
511 # argument: find arguments
512 # return: find results in an array $x
513 while read -rd ''; do
514 x+=("$REPLY");
515 done < <(find "$@" -print0);
516 }
517
518 faf() { # find all files. use -L to follow symlinks
519 find $@ -not \( -name .svn -prune -o -name .git -prune \
520 -o -name .hg -prune -o -name .editor-backups -prune \
521 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
522 }
523
524 # mail related
525 frozen() {
526 rm -rf /tmp/frozen
527 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
528 sudo exim -Mvl $id
529 echo
530 sudo exim -Mvh $id
531 echo
532 sudo exim -Mvb $id
533 echo -e '\n\n##############################\n'
534 done | tee -a /tmp/frozen
535 }
536 frozenrm() {
537 local ids=()
538 while read -r line; do
539 printf '%s\n' "$line"
540 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
541 done < <(s mailq)
542 echo "sleeping for 2 in case you change your mind"
543 sleep 2
544 sudo exim -Mrm "${ids[@]}"
545 }
546
547 funce() {
548 # like -e for functions. returns on error.
549 # at the end of the function, disable with:
550 # trap ERR
551 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
552 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
553 trap ERR
554 return' ERR
555 }
556
557 getdir () {
558 local help="Usage: getdir [--help] PATH
559 Output the directory of PATH, or just PATH if it is a directory."
560 if [[ $1 == --help ]]; then
561 echo "$help"
562 return 0
563 fi
564 if [[ $# -ne 1 ]]; then
565 echo "getdir error: expected 1 argument, got $#"
566 return 1
567 fi
568 if [[ -d $1 ]]; then
569 echo "$1"
570 else
571 local dir
572 dir="$(dirname "$1")"
573 if [[ -d $dir ]]; then
574 echo "$dir"
575 else
576 echo "getdir error: directory does not exist"
577 return 1
578 fi
579 fi
580 }
581
582 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
583 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
584 local root
585 root=$(gitroot) || return 1 # function to set gitroot
586 builtin cd "$root"
587 git symbolic-ref HEAD refs/heads/$1
588 rm .git/index
589 git clean -fdx
590 }
591
592 # shellcheck disable=SC2120
593 gitroot() {
594 local help="Usage: gitroot [--help]
595 Print the full path to the root of the current git repo
596
597 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
598 and works in older versions of git which did not have that."
599 if [[ $1 == --help ]]; then
600 echo "$help"
601 return
602 fi
603 local p
604 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
605 [[ $p != /* ]] && p=$PWD
606 echo "${p%%/.git}"
607 }
608
609 gh() {
610 # i got an error, gh not found when doing a pull request, it seems like it wants itself in it\'s path.
611 local _oldpath="$PATH"
612 PATH="$PATH:$HOME/node_modules/.bin"
613 command gh "$@"
614 PATH="$_oldpath"
615 }
616
617 gmacs() {
618 # quit will prompt if the program crashes.
619 gdb -ex=r -ex=quit --args emacs "$@"; r;
620 }
621
622 gdkill() {
623 # kill the emacs daemon
624 pk1 emacs --daemon
625 }
626
627 gr() {
628 grep -iIP --color=auto "$@"
629 }
630
631 grr() { # grep recursive
632 # Don't return 1 on nonmatch because this is meant to be
633 # interactive, not in a conditional.
634 if [[ ${#@} == 1 ]]; then
635 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" . || [[ $? == 1 ]]
636 else
637 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" || [[ $? == 1 ]]
638 fi
639 }
640 rg() {
641 command rg -i -M 200 "$@"
642 }
643
644 hr() { # horizontal row. used to break up output
645
646 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
647 echo
648 }
649
650 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
651
652 # get latest hub and run it
653 # main command to use:
654 # hub pull-request --no-edit
655 # --no-edit means to use the first commit\'s message as the pull request message.
656 # Also, you need to use a feature branch, not master in your fork.
657 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
658 # it\'s at ~/.config/hub
659 hub() {
660 local up uptar updir p
661 p=/github/hub/releases/
662 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
663 uptar=${up##*/}
664 updir=${uptar%.tgz}
665 if [[ ! -e /a/opt/$updir ]]; then
666 rm -rf /a/opt/hub-linux-amd64*
667 wget -P /a/opt $up
668 tar -C /a/opt -zxf /a/opt/$uptar
669 rm -f /a/opt/$uptar
670 sudo /a/opt/$updir/install
671 fi
672
673 # save token across computers
674 if [[ ! -L ~/.config/hub ]]; then
675 if [[ -e ~/.config/hub ]]; then
676 mv ~/.config/hub /p/c/subdir_files/.config/
677 fi
678 if [[ -e /p/c/subdir_files/.config/hub ]]; then
679 conflink
680 fi
681 fi
682 command hub "$@"
683 }
684
685 i() { git "$@"; }
686 # modified from ~/local/bin/git-completion.bash
687 # other completion commands are mostly taken from bash_completion package
688 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
689 || complete -o default -o nospace -F _git i
690
691 if ! type service &>/dev/null; then
692 service() {
693 echo actually running: systemctl $2 $1
694 systemctl $2 $1
695 }
696 fi
697
698
699
700 ic() {
701 # fast commit all
702 git commit -am "$*"
703 }
704
705
706
707 ifn() {
708 # insensitive find
709 find -L . -not \( -name .svn -prune -o -name .git -prune \
710 -o -name .hg -prune -o -name .editor-backups -prune \
711 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
712 }
713
714 ipdrop() {
715 sudo iptables -A INPUT -s $1 -j DROP
716 }
717
718
719 istext() {
720 grep -Il "" "$@" &>/dev/null
721 }
722
723 jtail() {
724 journalctl -n 10000 -f "$@"
725 }
726 jr() { journalctl "$@" ; }
727 jrf() { journalctl -f "$@" ; }
728
729 l() {
730 if [[ $PWD == /[iap] ]]; then
731 command ls -A --color=auto -I lost+found "$@"
732 else
733 command ls -A --color=auto "$@"
734 fi
735 }
736
737
738 lcn() { locate -i "*$**"; }
739
740 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first; }
741
742 lt() { ll -tr "$@"; }
743
744 lld() { ll -d "$@"; }
745
746 low() { # make filenames lowercase, remove bad chars
747 local f new
748 for f in "$@"; do
749 new="${f,,}" # downcase
750 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
751 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
752 new="${new%"${new##*[[:alnum:]]}"}"
753 # remove bad underscores, like __ and _._
754 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
755 safe_rename "$f" "$new" || return 1
756 done
757 return 0
758 }
759
760 lower() { # make first letter of filenames lowercase.
761 local x
762 for x in "$@"; do
763 if [[ ${x::1} == [A-Z] ]]; then
764 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
765 safe_rename "$x" "$y" || return 1
766 fi
767 done
768 }
769
770
771 k() { # history search
772 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
773 }
774
775 ks() { # history search
776 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
777 }
778
779
780 make-targets() {
781 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
782 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
783 }
784
785 mkc() {
786 mkdir "$1"
787 c "$1"
788 }
789
790 mkct() {
791 mkc $(mktemp -d)
792 }
793
794 mkt() { # mkdir and touch file
795 local path="$1"
796 mkdir -p "$(dirname "$path")"
797 touch "$path"
798 }
799
800 # shellcheck disable=SC2032
801 mkdir() { command mkdir -p "$@"; }
802
803 nopanic() {
804 # shellcheck disable=SC2024
805 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
806 }
807
808 p8() { ping 8.8.8.8; }
809 p6() { ping6 2001:4860:4860::8888; }
810
811 pkx() { # package extract
812 local pkg cached tmp f
813 c $(mktemp -d)
814 pkg=$1
815 # shellcheck disable=SC2012
816 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
817 if [[ $cached ]]; then
818 cp $cached .
819 else
820 aptitude download $pkg || return 1
821 fi
822 tmp=(*); f=${tmp[0]} # only 1 expected
823 ex $f
824 rm -f $f
825 }
826
827 # pgrep and kill
828 pk1() {
829 local pid
830 pid=($(pgrep -f "$*"))
831 case ${#pid[@]} in
832 1)
833 # shellcheck disable=SC2128
834 {
835 ps -F $pid
836 m kill $pid
837 }
838 ;;
839 0) echo "no pid found" ;;
840 *)
841 ps -F ${pid[@]}
842 ;;
843 esac
844 }
845
846 psg () {
847 local x y help
848 help="Usage: psg [--help] GREP_ARGS
849 grep ps and output in a nice format"
850 if [[ $1 == --help ]]; then
851 echo "$help"
852 return
853 fi
854 x=$(sudo ps -eF)
855 # final grep is because some commands tend to have a lot of trailing spaces
856 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
857 if [[ $y ]]; then
858 echo "$x" | head -n 1 || [[ $? == 141 ]]
859 echo "$y"
860 fi
861 }
862
863 pubip() { curl -4s https://icanhazip.com; }
864 pubip6() { curl -6s https://icanhazip.com; }
865 whatismyip() { pubip; }
866
867 pwgen() {
868 # -m = min length
869 # -x = max length
870 # -t = print pronunciation
871 apg -m 14 -x 17 -t
872 for (( i=0; i<10; i++ )); do
873 shuf -n3 /usr/share/hunspell/en_US.dic | sed 's,/.*,,' | paste -sd . -
874
875 done
876 }
877
878 pwlong() {
879 # -M CLN = use Caps, Lowercase, Numbers
880 # -n 1 = 1 password
881 # -a 1 = use random instead of pronounceable algorithm
882 apg -m 50 -x 70 -n 1 -a 1 -M CLN
883 }
884
885
886 q() { # start / launch a program in the backround and redir output to null
887 "$@" &> /dev/null &
888 }
889
890 # shellcheck disable=SC2120
891 r() {
892 if [[ $HISTFILE ]]; then
893 history -a # save history
894 fi
895 trap ERR # this avoids a segfault
896 exit ${1:0}
897 # i had this redir, not sure why
898 # exit "$@" 2>/dev/null
899 }
900
901 rl() {
902 # rsync, root is required to keep permissions right.
903 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
904 # --no-times --delete
905 # basically, make an exact copy, use checksums instead of file times to be more accurate
906 rsync -ahvic --delete "$@"
907 }
908 rld() {
909 # like rlu, but dont delete files on the target end which
910 # do not exist on the original end.
911 rsync -ahvic "$@"
912 }
913 complete -F _rsync -o nospace rld rl rlt
914
915 rlt() {
916 # rl without preserving modification time.
917 rsync -ahvic --delete --no-t "$@"
918 }
919
920 rlu() { # [OPTS] HOST PATH
921 # eg. rlu -opts frodo /testpath
922 # relative paths will expanded with readlink -f.
923 opts=("${@:1:$#-2}") # 1 to last -2
924 path="${*:$#}" # last
925 host="${*:$#-1:1}" # last -1
926 if [[ $path == .* ]]; then
927 path=$(readlink -f $path)
928 fi
929 # rync here uses checksum instead of time so we dont mess with
930 # unison relying on time as much. g is for group, same reason
931 # to keep up with unison.
932 sudo rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
933 }
934
935 rmstrips() {
936 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
937 }
938
939 s() {
940 # background
941 # I use a function because otherwise we cant use in a script,
942 # cant assign to variable.
943 #
944 # note: gksudo is recommended for X apps because it does not set the
945 # home directory to the same, and thus apps writing to ~ fuck things up
946 # with root owned files.
947 #
948 if [[ $EUID != 0 || $1 == -* ]]; then
949 # shellcheck disable=SC2034
950 SUDOD="$PWD" command sudo -i "$@"
951 else
952 "$@"
953 fi
954 }
955
956 safe_rename() { # warn and dont rename if file exists.
957 # mv -n exists, but it\'s silent
958 if [[ $# != 2 ]]; then
959 echo safe_rename error: $# args, need 2 >2
960 return 1
961 fi
962 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
963 if [[ -e $2 || -L $2 ]]; then
964 echo "Cannot rename $1 to $2 as it already exists."
965 else
966 mv -vi "$1" "$2"
967 fi
968 fi
969 }
970
971
972 sb() { # sudo bash -c
973 # use sb instead of s is for sudo redirections,
974 # eg. sb 'echo "ok fine" > /etc/file'
975 local SUDOD="$PWD"
976 sudo -i bash -c "$@"
977 }
978 complete -F _root_command s sb
979
980
981 ser() {
982 local s; [[ $EUID != 0 ]] && s=sudo
983 if type -p systemctl &>/dev/null; then
984 $s systemctl $1 $2
985 else
986 $s service $2 $1
987 fi
988 }
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
1027 sgu() {
1028 systemctl list-unit-files | rg "$@"
1029 }
1030
1031
1032 sk() {
1033 # 2086: unquoted $var
1034 # 2046: unquoted $(cmd)
1035 # 2068: Double quote array expansions to avoid re-splitting elements.
1036 # 2119: Functions with optional args get bad warnings when none are passed.
1037 # 2033: too many false positives for thing that will never work, passing shell function to find.
1038 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1039 shellcheck -x -e 2086,2046,2068,2119,2033 "$@" || return $?
1040 # had this before. not sure what it is 2119
1041 }
1042
1043
1044 slog() {
1045 # log with script. timing is $1.t and script is $1.s
1046 # -l to save to ~/typescripts/
1047 # -t to add a timestamp to the filenames
1048 local logdir do_stamp arg_base
1049 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1050 logdir="/a/dt/"
1051 do_stamp=false
1052 while getopts "lt" option
1053 do
1054 case $option in
1055 l ) arg_base=$logdir ;;
1056 t ) do_stamp=true ;;
1057 esac
1058 done
1059 shift $((OPTIND - 1))
1060 arg_base+=$1
1061 [[ -e $logdir ]] || mkdir -p $logdir
1062 $do_stamp && arg_base+=$(date +%F.%T%z)
1063 script -t $arg_base.s 2> $arg_base.t
1064 }
1065 splay() { # script replay
1066 #logRoot="$HOME/typescripts/"
1067 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1068 scriptreplay "$1.t" "$1.s"
1069 }
1070
1071 sr() {
1072 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1073 if [[ $# == 0 ]]; then
1074 sudo -E bash -c -l "$(history -p '!!')"
1075 else
1076 echo this command redos last history item. no argument is accepted
1077 fi
1078 }
1079
1080 srm () {
1081 # with -ll, less secure but faster.
1082 command srm -ll "$@"
1083 }
1084
1085 srun() {
1086 scp $2 $1:/tmp
1087 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1088 }
1089
1090
1091 swap() {
1092 local tmp
1093 tmp=$(mktemp)
1094 mv $1 $tmp
1095 mv $2 $1
1096 mv $tmp $2
1097 }
1098
1099 tclock() { # terminal clock
1100 local x
1101 clear
1102 date +%l:%_M
1103 len=60
1104 # this goes to full width
1105 #len=${1:-$((COLUMNS -7))}
1106 x=1
1107 while true; do
1108 if (( x == len )); then
1109 end=true
1110 d="$(date +%l:%_M) "
1111 else
1112 end=false
1113 d=$(date +%l:%M:%_S)
1114 fi
1115 echo -en "\r"
1116 echo -n "$d"
1117 for ((i=0; i<x; i++)); do
1118 if (( i % 6 )); then
1119 echo -n _
1120 else
1121 echo -n .
1122 fi
1123 done
1124 if $end; then
1125 echo
1126 x=1
1127 else
1128 x=$((x+1))
1129 fi
1130 sleep 5
1131 done
1132 }
1133
1134
1135 te() {
1136 # test existence / exists
1137 local ret=0
1138 for x in "$@"; do
1139 [[ -e "$x" || -L "$x" ]] || ret=1
1140 done
1141 return $ret
1142 }
1143
1144
1145 tx() { # toggle set -x, and the prompt so it doesnt spam
1146 if [[ $- == *x* ]]; then
1147 set +x
1148 PROMPT_COMMAND=prompt-command
1149 # disabled due to issue on stretch, running ll we get error. something
1150 # about the DEBUG trap is broken
1151 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1152 # trap 'settitle "$BASH_COMMAND"' DEBUG
1153 # fi
1154 else
1155 # normally, i would just execute these commands in the function.
1156 # however, DEBUG is not inherited, so we need to run it outside a function.
1157 # And we want to run set -x afterwards to avoid spam, so we cram everything
1158 # in here, and then it will run after this function is done.
1159 #PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "; set -x'
1160
1161 unset PROMPT_COMMAND
1162 PS1="\w \$ "
1163 set -x
1164 fi
1165 }
1166
1167 psnetns() {
1168 # show all processes in the network namespace $1.
1169 # blank entries appear to be subprocesses/threads
1170 local x netns
1171 netns=$1
1172 ps -w | head -n 1
1173 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1174 while read -r l; do
1175 x=$(ps -w --no-headers -p $l);
1176 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1177 done
1178 }
1179
1180 m() { printf "%s\n" "$*"; "$@"; }
1181
1182
1183 virshrm() {
1184 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1185 }
1186
1187 vm-set-listen(){
1188 local t
1189 t=$(mktemp)
1190 local vm=$1
1191 local ip=$2
1192 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1193 sed -r "s/listen='[^']+/listen='$ip/"> $t
1194 sudo virsh undefine $vm
1195 sudo virsh define $t
1196 }
1197
1198
1199 vmshare() {
1200 vm-set-listen $1 0.0.0.0
1201 }
1202
1203
1204 vmunshare() {
1205 vm-set-listen $1 127.0.0.1
1206 }
1207
1208 # * misc stuff
1209
1210
1211 # temporary variables to test colorization
1212 # some copied from gentoo /etc/bash/bashrc,
1213 use_color=false
1214 # dircolors --print-database uses its own built-in database
1215 # instead of using /etc/DIR_COLORS. Try to use the external file
1216 # first to take advantage of user additions.
1217 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1218 match_lhs=""
1219 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1220 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1221 [[ -z ${match_lhs} ]] \
1222 && type -P dircolors >/dev/null \
1223 && match_lhs=$(dircolors --print-database)
1224 # test if our $TERM is in the TERM values in dircolor
1225 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1226
1227
1228 if ${use_color} && [[ $- == *i* ]]; then
1229
1230 term_bold="$(tput bold)"
1231 term_red="$(tput setaf 1)"
1232 term_green="$(tput setaf 2)"
1233 term_yellow="$(tput setaf 3)"
1234 term_purple="$(tput setaf 5)"
1235 term_nocolor="$(tput sgr0)" # no font attributes
1236
1237 # unused so far. commented for shellcheck
1238 # term_underl="$(tput smul)"
1239 # term_blue="$(tput setaf 4)"
1240 # term_cyan="$(tput setaf 6)"
1241
1242 fi
1243 # Try to keep environment pollution down, EPA loves us.
1244 unset safe_term match_lhs use_color
1245
1246 # * prompt
1247
1248
1249 if [[ $- == *i* ]]; then
1250
1251 # this needs to come before next ps1 stuff
1252 # this stuff needs bash 4, feb 2009,
1253 # old enough to no longer condition on $BASH_VERSION anymore
1254 shopt -s autocd
1255 shopt -s dirspell
1256 PS1='\w'
1257 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1258 PROMPT_DIRTRIM=2
1259 bind -m vi-command B:shell-backward-word
1260 bind -m vi-command W:shell-forward-word
1261 fi
1262
1263 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1264 PS1="\h $PS1"
1265 fi
1266
1267 # emacs terminal has problems if this runs slowly,
1268 # so I've thrown a bunch of things at the wall to speed it up.
1269 prompt-command() {
1270 local return=$? # this MUST COME FIRST
1271 local ps_char ps_color
1272 unset IFS
1273
1274 if [[ $HISTFILE ]]; then
1275 history -a # save history
1276 fi
1277
1278 if [[ $jr_pid ]]; then
1279 if [[ -e /proc/$jr_pid ]]; then
1280 kill $jr_pid
1281 fi
1282 unset jr_pid
1283 fi
1284
1285 case $return in
1286 0) ps_color="$term_purple"
1287 ps_char='\$'
1288 ;;
1289 1) ps_color="$term_green"
1290 ps_char="$return \\$"
1291 ;;
1292 *) ps_color="$term_yellow"
1293 ps_char="$return \\$"
1294 ;;
1295 esac
1296 if [[ ! -O . ]]; then # not owner
1297 if [[ -w . ]]; then # writable
1298 ps_color="$term_bold$term_red"
1299 else
1300 ps_color="$term_bold$term_green"
1301 fi
1302 fi
1303
1304 # faster than sourceing the file im guessing
1305 if [[ -e /dev/shm/iank-status ]]; then
1306 eval $(< /dev/shm/iank-status)
1307 fi
1308 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1309 ps_char="@ $ps_char"
1310 fi
1311 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1312 }
1313 PROMPT_COMMAND=prompt-command
1314
1315 settitle () {
1316 if [[ $TERM == screen* ]]; then
1317 local title_escape="\033]..2;"
1318 else
1319 local title_escape="\033]0;"
1320 fi
1321 if [[ $0 != prompt-command ]]; then
1322 echo -ne "$title_escape$USER@$HOSTNAME ${PWD/#$HOME/~} "
1323 printf "%s" "$*"
1324 echo -ne "\007"
1325 fi
1326 }
1327
1328 # for titlebar.
1329 # condition from the screen man page i think.
1330 # note: duplicated in tx()
1331 # disabled. see note in tx
1332 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1333 # trap 'settitle "$BASH_COMMAND"' DEBUG
1334 # else
1335 # trap DEBUG
1336 # fi
1337
1338 fi
1339
1340 # * stuff that makes sense to be at the end
1341
1342
1343 # best practice
1344 unset IFS
1345
1346 # shellcheck disable=SC1090
1347 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
1348
1349 # I had this idea to start a bash shell which would run an initial
1350 # command passed through this env variable, then continue on
1351 # interactively. But the use case I had in mind went away.
1352 #
1353 # if [[ $MY_INIT_CMD ]]; then
1354 # "${MY_INIT_CMD[@]}"
1355 # unset MY_INIT_CMD
1356 # fi
1357
1358 # ensure no bad programs appending to this file will have an affect
1359 return 0