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