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