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